My data consist of an identifier (srdr_id), and a list column.
dat <- structure(list(srdr_id = c("174136", "174258", "174684"), outcomes = list(
structure(list(outcome_s = c("use_alcohol", "use_cannabis",
"use_cocaine")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-3L)), structure(list(outcome_s = "use_methamphetamine"), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -1L)), structure(list(
outcome_s = c("use_alcohol", "use_heavy")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -2L)))), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -3L))
> dat
# A tibble: 3 x 2
srdr_id outcomes
<chr> <list>
1 174136 <tibble [3 x 1]>
2 174258 <tibble [1 x 1]>
3 174684 <tibble [2 x 1]>
I would like to convert each tibble in outcomes to a single comma separated string.
You can also use a map
function to iterate over the list-column, pulling out the first column of each tibble and collapsing into a single string:
library(tidyverse)
dat <- structure(list(srdr_id = c("174136", "174258", "174684"), outcomes = list(structure(list(outcome_s = c("use_alcohol", "use_cannabis", "use_cocaine")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -3L)), structure(list(outcome_s = "use_methamphetamine"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -1L)), structure(list(outcome_s = c("use_alcohol", "use_heavy")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L)))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -3L))
dat %>%
mutate(outcomes = map_chr(outcomes, ~ .[[1]] %>% str_c(collapse = ", ")))
#> # A tibble: 3 x 2
#> srdr_id outcomes
#> <chr> <chr>
#> 1 174136 use_alcohol, use_cannabis, use_cocaine
#> 2 174258 use_methamphetamine
#> 3 174684 use_alcohol, use_heavy
Created on 2019-05-13 by the reprex package (v0.2.1)
You can now use
dat %>% rowwise() %>%
mutate(outcomes = paste(outcomes, collapse=',')) %>%
ungroup()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With