Home > Back-end >  R create new column based on a condition from 2 columns
R create new column based on a condition from 2 columns

Time:10-13

I have a dataframe with this structure:

id v1 v1_2
1  4  .    
2  5  .    
3  9  7    
4  9  6     
5  2  .    

And what I would like is to create a new column based on values from v1 and v1_2, so basically keeping the original value and if the original value is 9 then use the column of v1_2

id v1 v1_2 final
1  4  .    4
2  5  .    5
3  9  7    7
4  9  6    6 
5  2  .    2

Thanks

CodePudding user response:

Use ifelse

df$final <- with(df, ifelse(v1 == 9, v1_2, v1))

CodePudding user response:

Here is an alternative dplyr way:

library(dplyr)
na_if(df, ".") %>% 
  type.convert(as.is=TRUE) %>% 
  mutate(final= coalesce(v1_2,v1))
  id v1 v1_2 final
1  1  4   NA     4
2  2  5   NA     5
3  3  9    7     7
4  4  9    6     6
5  5  2   NA     2

CodePudding user response:

A tidyverse approach:

library(dplyr)

df %>% 
  mutate(final = if_else(v1 == 9, v1_2, v1))
  • Related