1

Column 1

1 <=
2 <=
3 =
4 <=
5 =
6 >
7 <=
8 =
9 <=
10 =

Column 2

1 0.5
2 0.5
3 8
4 0.5
5 1
6 32
7 0.5
8 1
9 0.5
10 8

I need column 3.

I know this will not work in R, but this is what I want to get.

mutate(if(col1 = "<="){
  start <- 0
} else if(col1 = "="){
  start <- col2/2
} else if(col1 = ">"){
  start <- paste(col2)
})

Data:

structure(list(`col1` = c("<=", "<=", "=", "<=", "=", ">"
), col2 = c("0.5", "0.5", "8", "0.5", "1", "32")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))
Phil
  • 7,287
  • 3
  • 36
  • 66
  • 1
    Using `dplyr`: `mutate(dataframe, col3 = case_when(col1 == "<=" ~ 0, col1 == "=" ~ col2/2, col1 == ">" ~ col2))` – Phil Jun 16 '20 at 14:12
  • 1
    Does this answer your question? [Can dplyr package be used for conditional mutating?](https://stackoverflow.com/questions/24459752/can-dplyr-package-be-used-for-conditional-mutating) – divibisan Jun 16 '20 at 14:19
  • This error appears: Problem with `mutate()` input `Col3`. x non-numeric argument to binary operator i Input `Col3` is `case_when(...)`. Backtrace: x 1. +-dplyr::mutate(...) 2. \-dplyr:::mutate.data.frame(...) 3. \-dplyr:::mutate_cols(.data, ...) non-numeric argument to binary operator – Angelica Collins Jun 16 '20 at 14:26
  • Could you please run the command dput(head(nameofyourdataframe)) and edit your question to include it – Chuck P Jun 16 '20 at 14:34
  • Thank you adjusted my answer – Chuck P Jun 16 '20 at 15:01

1 Answers1

2

With adjustment for your dput


library(dplyr)

mydata %>% mutate(start = case_when(
  col1 == "<=" ~ 0,
  col1 == "=" ~ as.numeric(col2) / 2,
  col1 == ">" ~ as.numeric(col2),
  TRUE ~ NA_real_
))


# A tibble: 6 x 3
  col1  col2  start
  <chr> <chr> <dbl>
1 <=    0.5     0  
2 <=    0.5     0  
3 =     8       4  
4 <=    0.5     0  
5 =     1       0.5
6 >     32     32  
Chuck P
  • 3,862
  • 3
  • 9
  • 20