使用 purrr 方式将列出的列转换为 R 中的字符串

Using purrr way to convert listed columns to string in R

我试图将列有向量的列转换为字符串。我不想使用 pivot_wider 使数据帧变宽,而是想取消列出向量并将它们保存在同一个单元格中。因此数据框具有相同数量的列。我找到了使用 sapply 转换一列的解决方案。

df$a <- sapply(df$a, paste, collapse=",")

我想知道是否有办法以 purrr 的方式对列出的多个列执行此操作。我已经提供了我的输入。

structure(list(rowid = c(3995L, 7899L), a = list(c("", "3007766601", 
"1710034", "1036761", "3006260740", "9681413", "3004080548", 
"1018470", "3010966701"), c("3013099020", "", "3005254598", "3007556128", 
"3003600763", "3011347852")), e = list(c("K172483", 
"K992729", "K043249", "K072487", "K033575", "K011925", "K180588", 
"K982399", "K150662", "K110703"), c("K913525", "K880518", "K960198", 
"K141672", "K926056", "K935580", "K953910", "K982706", "K911739", 
"K010762", "K965013", "K120388", "K760429", "K940294", "K980322", 
"K981131", "K896387", "K170946", "K003266", "K992506", "K003837", 
"K121303", "K123603", "K190024"))), row.names = c(3995L, 7899L
), class = "data.frame")

您可以使用两个 sapply:

sapply(df, function(x) sapply(x, paste, collapse=","))
#     rowid  a                                                                              e                                                                                                                                                                                                
#[1,] "3995" ",3007766601,1710034,1036761,3006260740,9681413,3004080548,1018470,3010966701" "K172483,K992729,K043249,K072487,K033575,K011925,K180588,K982399,K150662,K110703"                                                                                                                
#[2,] "7899" "3013099020,,3005254598,3007556128,3003600763,3011347852"                      "K913525,K880518,K960198,K141672,K926056,K935580,K953910,K982706,K911739,K010762,K965013,K120388,K760429,K940294,K980322,K981131,K896387,K170946,K003266,K992506,K003837,K121303,K123603,K190024"

使用 purrr

中的 map
library(purrr)
library(stringr)
map_dfr(df, ~ map_chr(.x, str_c, collapse=", "))

-输出

# A tibble: 2 x 3
#  rowid a                                                    e                                                                                        
#  <chr> <chr>                                                <chr>                                                                                    
#1 3995  , 3007766601, 1710034, 1036761, 3006260740, 9681413… K172483, K992729, K043249, K072487, K033575, K011925, K180588, K982399, K150662, K110703 
#2 7899  3013099020, , 3005254598, 3007556128, 3003600763, 3… K913525, K880518, K960198, K141672, K926056, K935580, K953910, K982706, K911739, K010762…