R replace multiple columns based on multiple conditions

Viewed 141

I'm trying to replace multiple column based on multiple conditions :

test=data.frame(
  start=c(1,100,1000,10000),
  end=c(10,110,1010,10010),
  value=c(-1.2,-1.5,-1.02,-0.5),
  substart=c(2,102,NA,NA),
  subend=c(8,108,NA,NA)
)

If value is <= -1 and substart == NA :
I want that : substart = start and subend = end 

This is the desired output :

  start   end value substart subend
     1    10 -1.20        2      8
   100   110 -1.50      102    108
  1000  1010 -1.02     1000   1010
 10000 10010 -0.50       NA     NA

I'm trying to use dplyr but I'm not getting what I want and also it's better if I can change them all in one command

test %>%
  mutate(substart=replace_na(substart, (value<=-1 & substart =='NA'), start))

Thanks !

2 Answers

Try this:

test %>% 
   mutate(substart = ifelse(value <= -1 & is.na(substart),start,substart),
          subend = ifelse(value <= -1 & is.na(subend),end,subend))

here is a version using case_when() from dplyr which can handle multiple conditions, although only the single condition asked for by the OP is shown here:

library(dplyr)

testdf <- data.frame(
  start=c(1,100,1000,10000),
  end=c(10,110,1010,10010),
  value=c(-1.2,-1.5,-1.02,-0.5),
  substart=c(2,102,NA,NA),
  subend=c(8,108,NA,NA)
)

testdf %>% 
  mutate(substart=case_when(value <= -1 & is.na(substart) ~ start,
                            TRUE ~ substart),
         subend=case_when(value <= -1 & is.na(subend) ~ end,
                            TRUE ~ subend))

which has the desired output:

  start   end value substart subend
1     1    10 -1.20        2      8
2   100   110 -1.50      102    108
3  1000  1010 -1.02     1000   1010
4 10000 10010 -0.50       NA     NA
Related