我有适用于我脚本的合格列的向量
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应该为字符串,如果其中一些不是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(而不是dplyr
)中进行此操作:
result$res <- apply(result[,cols],1, function(x){paste(cols[!is.na(x)], collapse=", ")})
result$res[results$res==""] <- "nothing"
您共享的数据不同(test
和result
)。因此,我们将从删除result
列开始于res
。
library(dplyr)
result$res <- NULL
result %>%
mutate_all(as.character) %>%
tidyr::pivot_longer(cols = cols) %>%
group_by(id) %>%
summarise(res = toString(name[!is.na(value)])) %>%
type.convert() %>%
left_join(res, by = 'id') %>%
mutate(res = case_when(res == '' ~ 'nothing',
stringr::str_count(result, ',') ==
(length(cols) - 1) ~ 'all',
TRUE ~ as.character(result)))
# A tibble: 3 x 5
# id res country phone car
# <dbl> <chr> <fct> <dbl> <lgl>
#1 1 country, phone us 1 NA
#2 2 phone NA 1 NA
#3 3 nothing NA NA NA
我们获取长格式的数据,获取每个ID
具有非NA值的列名。然后,如果分别存在全部或0个匹配项,则将res
列更改为"all"
或"nothing"
。