gpt4 book ai didi

r - 如何创建列值为 TRUE 的列名列表列

转载 作者:行者123 更新时间:2023-12-03 21:06:56 25 4
gpt4 key购买 nike

我有一些多选问题的调查数据,这些数据与每个可能选择的列一起输出,填充了 TRUE/FALSE 值,例如

library(dplyr)

dat <- tribble(
~name, ~state, ~onions, ~`sweet potatoes`, ~garlic,
"Tom", "WV", TRUE, FALSE, TRUE,
"Larry", "NC", FALSE, TRUE, FALSE,
"Beth", "NY", TRUE, TRUE, TRUE
)

dat

#> name state onions `sweet potatoes` garlic
#> <chr> <chr> <lgl> <lgl> <lgl>
#> 1 Tom WV TRUE FALSE TRUE
#> 2 Larry NC FALSE TRUE FALSE
#> 3 Beth NY TRUE TRUE TRUE

如何创建包含受访者回答“TRUE”的列名称的列表列?
类似于 https://stackoverflow.com/a/9508203/1009730
我已经尝试了几个关于主题的变体
dat %>%
rowwise() %>%
mutate(fav_foods = list(names(which(~ is.logical(.x) && .x))))
这给出了错误:

Error: Problem with mutate() input fav_foods. x argument to 'which' is not logical i Input fav_foods is list(names(which(~is.logical(.x) && .x))). i The error occurred in row 1.

最佳答案

添加 purrr ,你可以这样做:

dat %>%
mutate(fav_foods = pmap_chr(across(where(is.logical)), ~ toString(names(c(...))[which(c(...))])))

name state onions `sweet potatoes` garlic fav_foods
<chr> <chr> <lgl> <lgl> <lgl> <chr>
1 Tom WV TRUE FALSE TRUE onions, garlic
2 Larry NC FALSE TRUE FALSE sweet potatoes
3 Beth NY TRUE TRUE TRUE onions, sweet potatoes, garlic
或者,如果您需要将其作为列表:
dat %>%
mutate(fav_foods = pmap(across(where(is.logical)), ~ names(c(...))[which(c(...))]))

name state onions `sweet potatoes` garlic fav_foods
<chr> <chr> <lgl> <lgl> <lgl> <list>
1 Tom WV TRUE FALSE TRUE <chr [2]>
2 Larry NC FALSE TRUE FALSE <chr [1]>
3 Beth NY TRUE TRUE TRUE <chr [3]>

关于r - 如何创建列值为 TRUE 的列名列表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66250764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com