Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将列表列转换为字符串列_R_Dplyr_Tostring_Purrr - Fatal编程技术网

R 将列表列转换为字符串列

R 将列表列转换为字符串列,r,dplyr,tostring,purrr,R,Dplyr,Tostring,Purrr,我的数据由一个标识符(srdr_id)和一个列表列组成 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

我的数据由一个标识符(srdr_id)和一个列表列组成

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]>
dat-dat
#一个tibble:3x2
srdr_id成果
1 174136  
2 174258  
3 174684  
我想将结果中的每个tibble转换为一个逗号分隔的字符串


这里有一种使用
tidyverse的方法-

dat %>% 
  unnest(outcomes) %>% 
  group_by(srdr_id) %>% 
  summarise(
    outcomes = toString(outcome_s)
  )

# 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        
dat%>%
未测试(结果)%>%
分组依据(srdr id)%>%
总结(
结果=toString(结果)
)
#一个tibble:3x2
srdr_id成果
1 174136使用酒精、大麻、可卡因
2 174258使用甲基苯丙胺
3 174684使用酒精,使用重型

您还可以使用
map
函数迭代列表列,拉出每个TIBLE的第一列并折叠成单个字符串:

库(tidyverse)
dat%
突变(结果=map_chr(结果,~.[1]]%>%str_c(collapse=“,”))
#>#tibble:3 x 2
#>srdr_id成果
#>                                       
#>1 174136使用酒精、大麻、可卡因
#>2 174258使用甲基苯丙胺
#>3 174684使用酒精,使用重型
由(v0.2.1)于2019-05-13创建,您现在可以使用

dat %>% rowwise() %>% 
    mutate(outcomes = paste(outcomes, collapse=',')) %>%
    ungroup()

如果在数据帧上调用
unnest
,它将成为