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