R语言 将列表分隔为列

w6lpcovy  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(200)

我在R中有这个列表:

my_list = list("word",c("word", "word"), "word", c("word", "word","word"), "word")

[[1]]
[1] "word"

[[2]]
[1] "word" "word"

[[3]]
[1] "word"

[[4]]
[1] "word" "word" "word"

[[5]]
[1] "word"

我想把这个列表转换成一个数据框,看起来像这样:

col1 col2 col3
1 word          
2 word word     
3 word          
4 word word word
5 word   

# source code of the desired output

structure(list(col1 = c("word", "word", "word", "word", "word"
), col2 = c("", "word", "", "word", ""), col3 = c("", "", "", 
"word", "")), class = "data.frame", row.names = c(NA, -5L))

我尝试使用此处提供的答案(How to split a column of list into several columns using R)来回答我的问题:

z = my_list
x <- do.call(rbind, z)
colnames(x) <- LETTERS[1:ncol(x)]
h = data.frame(cbind(z[c("sg", "time")], x))

但这并没有给我想要的输出。
谁能告诉我怎么做这个?
谢谢你,谢谢你

eeq64g8w

eeq64g8w1#

您可以使用lapply使列表元素的长度相同,然后使用do.callrbind创建所需的输出:

do.call(rbind, lapply(my_list, `length<-`, max(lengths(my_list))))

输出量

#      [,1]   [,2]   [,3]  
# [1,] "word" NA     NA    
# [2,] "word" "word" NA    
# [3,] "word" NA     NA    
# [4,] "word" "word" "word"
# [5,] "word" NA     NA

如果您希望有空白而不是NA值:

new_df <- do.call(rbind, lapply(my_list, `length<-`, max(lengths(my_list))))
new_df[is.na(new_df)] <- ""

输出量:

#      [,1]   [,2]   [,3]  
# [1,] "word" ""     ""    
# [2,] "word" "word" ""    
# [3,] "word" ""     ""    
# [4,] "word" "word" "word"
# [5,] "word" ""     ""
9rygscc1

9rygscc12#

使用stringi::stri_list2matrix

library(stringi)
data.frame(stri_list2matrix(my_list, byrow = TRUE))
#     X1   X2   X3
# 1 word <NA> <NA>
# 2 word word <NA>
# 3 word <NA> <NA>
# 4 word word word
# 5 word <NA> <NA>

或者用sapply表示:

t(sapply(my_list, "length<-", max(lengths(my_list))))

相关问题