简体   繁体   中英

Replace column condition dplyr

ID <- c("A","B","C","D","E")
AT <- c(0.1,0.2,0.3,0.4,0.5)
US <- c(NA,NA,0.6,NA,NA)
FIGX <- c(1,NA,NA,2,3)
W1 <- c(NA,10,20,30,40)
test.Data <- data.frame(ID,AT,US,FIGX,W1) %>% as.data.table()

I have this kind of table. I would like to replace the values of column US by values of FIGX if NA, and if FIGX is NA, then to replace by the W1 column values.

I have tried this test.Data %>% mutate_if(is.na(US),mutate_if(is.na(FIGX),W1)) without success. How should I do?

Here is an option with daa.table as the input data is already a data.table

library(data.table)
library(dplyr)
test.Data[is.na(US), US := coalesce(FIGX, W1)][]
test.Data
#   ID  AT   US FIGX W1
#1:  A 0.1  1.0    1 NA
#2:  B 0.2 10.0   NA 10
#3:  C 0.3  0.6   NA 20
#4:  D 0.4  2.0    2 30
#5:  E 0.5  3.0    3 40

For multiple columns, we can use set

colsOfInterest <- c("US", "AT")
for(nm in colsOfInterest){
   i1 <- which(is.na(test.Data[[nm]]))
   set(test.Data, i = i1 ,
         j = nm, value = coalesce(test.Data[["FIGX"]][i1], test.Data[["W1"]][i1]))
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM