I am trying to add a column to a table where the new column, called "ID", would contain 3-5 or 3.5 or 3/5, if column 1 contains the value 3 and column 2 contains the value 5.
CodePudding user response:
library(dplyr)
data %>% mutate(ID = paste0(column1,'-',column2))
you can change -
with any symbol you want.
CodePudding user response:
As noted by others, an ifelse
operation will be helpful:
Toy data:
df <- data.frame(
c1 = c(1,3,4,2,6,3,5),
c2 = c(2,5,3,0,2,5,5)
)
df$ID <- ifelse(df$c1 == 3 & df$c2 == 5, # condition to meet
paste(df$c1, df$c2, sep = "/"), # action if condition == TRUE
NA) # action if condition == FALSE
Result:
df
c1 c2 ID
1 1 2 <NA>
2 3 5 3/5
3 4 3 <NA>
4 2 0 <NA>
5 6 2 <NA>
6 3 5 3/5
7 5 5 <NA>