问题描述
我有一个字符串列表,如下所示:
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"
最长的列表的长度为2,我想从该列表中构建一个包含2列的数据框.积分还可以将列表中的每个项目转换为数字(或字符(0)不适用).我已经尝试过使用mapply()和data.frame转换为数据框,并用NA填充,如下所示.
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))
但是,我没有使用上面的代码获得包含 2 列(并且 NA 作为填充符)的数据框.
However, I do not get a data frame with 2 columns (and NA's as fillers) using the code above.
感谢您的帮助.
推荐答案
我们可以使用 stringi
中的 stri_list2matrix
.由于 list
元素都是 character
向量,因此可以使用此功能
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"
如果我们需要转换为 data.frame
,请用 as.data.frame
If we need to convert to data.frame
, wrap it with as.data.frame
这篇关于将字符串列表转换为R中的数字数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!