I've got some survey data for multiple-selection questions that has been output with a column for each possible selection, populated with TRUE/FALSE values, e.g.
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
How can I create a list-column containing the column names for which the respondents answered "TRUE"?
simliar to https://stackoverflow.com/a/9508203/1009730
I've tried several variations on the theme of
dat %>%
rowwise() %>%
mutate(fav_foods = list(names(which(~ is.logical(.x) && .x))))
which gives the error:
Error: Problem with
mutate()
inputfav_foods
. x argument to 'which' is not logical i Inputfav_foods
islist(names(which(~is.logical(.x) && .x)))
. i The error occurred in row 1.
With the addition of purrr
, you could do:
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
Or if you need it as a list:
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]>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments