Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list column to column of strings

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.

enter image description here

like image 865
user25494 Avatar asked Dec 31 '22 23:12

user25494


2 Answers

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)

like image 70
Calum You Avatar answered Jan 08 '23 01:01

Calum You


You can now use

dat %>% rowwise() %>% 
    mutate(outcomes = paste(outcomes, collapse=',')) %>%
    ungroup()
like image 22
geotheory Avatar answered Jan 08 '23 00:01

geotheory