【发布时间】:2020-07-18 04:41:09
【问题描述】:
我的脚本有这个符合条件的列向量
cols <- c("country", "phone", "car")
还有这个dataframe
test <-
data.frame(
id = c(1, 2, 3),
country = c("us", NA, "uk"),
phone = c(1, 1, NA),
car = c(NA, 0, 1)
)
目标是使用结果创建一个新列,其中条件将仅基于 cols 变量中存在的列。如果 id 的所有值都是NA,那么 res 应该是 string nothing,如果其中一些不是 NA,那么我需要这个 colnames,如果所有列都不是 NA,那么结果应该是 string all .
result <-
data.frame(
id = c(1, 2, 3),
country = c("us", NA, NA),
phone = c(1, 1, NA),
car = c(NA, NA, NA),
res = c("country, phone", "phone", "nothing")
)
我只能通过case_when()函数做到这一点
mutate(
res = case_when(
!is.na(country) & is.na(phone) & is.na(car) ~ "country",
T ~ "?"
)
【问题讨论】:
标签: r if-statement dplyr na