如何使用dplyr将data.frame的列表列转为逗号分隔字符串?
问题
现有如下tibble数据,需要将其中的color_names列(list类型)转换为逗号分隔的字符串,优先使用dplyr解决方案。
原始数据:
library(tibble) df <- tibble( col_hex = c("#0087BF", "#FF0000"), col_freq = c(87462L, 87019L), col_share = c(0.501269479198308, 0.498730520801692), color_names = list('deepskyblue3', c("red", "red1")) )
原始数据结构:
#> # A tibble: 2 x 4 #> col_hex col_freq col_share color_names #> <chr> <int> <dbl> <list> #> 1 #0087BF 87462 0.501 <chr [1]> #> 2 #FF0000 87019 0.499 <chr [2]>
期望输出:
#> # A tibble: 2 x 4 #> col_hex col_freq col_share color_names #> <chr> <int> <dbl> <chr> #> 1 #0087BF 87462 0.501 deepskyblue3 #> 2 #FF0000 87019 0.499 red, red1
dplyr解决方案
方案1:结合purrr包实现
用dplyr的mutate()配合purrr的map_chr(),对每个list元素执行字符串拼接:
library(dplyr) library(purrr) df_processed <- df %>% mutate(color_names = map_chr(color_names, ~paste(.x, collapse = ", ")))
方案2:仅用base R + dplyr实现
如果不想额外加载purrr包,可使用base R的vapply()完成相同操作:
library(dplyr) df_processed <- df %>% mutate(color_names = vapply(color_names, function(x) paste(x, collapse = ", "), character(1)))
处理后的数据结构验证:
df_processed #> # A tibble: 2 x 4 #> col_hex col_freq col_share color_names #> <chr> <int> <dbl> <chr> #> 1 #0087BF 87462 0.501 deepskyblue3 #> 2 #FF0000 87019 0.499 red, red1
内容的提问来源于stack exchange,提问作者joshbrows
相关产品推荐
相关产品推荐

