我在下面有一个数据框:
Step
预期输出:
df
ColA ColB ColC
NA BN 6
JH NA 8
NA rewr 9
NA NA 10
如何使用sqldf做到这一点?
这是我的尝试,但没有得到我想要的输出:
newdf
ColA ColB ColC New_Col
NA BN 6 BN
JH NA 8 JH
NA rewr 9 rewr
NA NA 10 NA
答案 0 :(得分:3)
使用coalesce
library(sqldf)
sqldf("SELECT ColA, ColB, ColC, coalesce(ColA, ColB) as New_Col from df")
# ColA ColB ColC New_Col
#1 <NA> BN 6 BN
#2 JH <NA> 8 JH
#3 <NA> rewr 9 rewr
#4 <NA> <NA> 10 <NA>
或与tidyverse
library(dplyr)
df %>%
mutate(New_Col = coalesce(ColA, ColB))
# ColA ColB ColC New_Col
#1 <NA> BN 6 BN
#2 JH <NA> 8 JH
#3 <NA> rewr 9 rewr
#4 <NA> <NA> 10 <NA>
df <- structure(list(ColA = c(NA, "JH", NA, NA), ColB = c("BN", NA,
"rewr", NA), ColC = c(6L, 8L, 9L, 10L)), class = "data.frame", row.names = c(NA,
-4L))