Converting a list of lists of strings to a data frame of numbers in R

蹲街弑〆低调 提交于 2021-02-10 16:02:33

问题


I have a list of lists of strings as follows:

> ll

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

[[2]]
character(0)

[[3]]
[1] "1"

[[4]]
[1] "1" "8"

The longest list is of length 2, and I want to build a data frame with 2 columns from this list. Bonus points for also converting each item in the list to a number or NA for character(0). I have tried using mapply() and data.frame to convert to a data frame and fill with NA's as follows.

#  Find length of each list element
len = sapply(awards2, length)

#  Number of NAs to fill for column shorter than longest
len = 2 - len

df = data.frame(mapply( function(x,y) c( x , rep( NA , y ) ) , ll , len))

However, I do not get a data frame with 2 columns (and NA's as fillers) using the code above.

Thanks for the help.


回答1:


We can use stri_list2matrix from stringi. As the list elements are all character vectors, it seems okay to use this function

library(stringi)
t(stri_list2matrix(ll))
#     [,1] [,2]
#[1,] "2"  "1" 
#[2,] NA   NA  
#[3,] "1"  NA  
#[4,] "1"  "8" 

If we need to convert to data.frame, wrap it with as.data.frame



来源:https://stackoverflow.com/questions/42514249/converting-a-list-of-lists-of-strings-to-a-data-frame-of-numbers-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!