2016-10-19 57 views
1

我有一个400,000个不同长度的字符向量的列表,我想将这个列表转换为一列data.frame,每行都是从原始字符向量连接起来的一串字符。将各种长度的字符向量列表转换为一列data.frame中R

这里是一个例子。

lst <- list() 

lst[[1]] <- letters[1:7] 
lst[[2]] <- letters[3:5] 
lst[[3]] <- LETTERS[15:26] 
lst[[4]] <- letters[4:12] 

我这个列表转换为data.frame这样的:

df <- as.data.frame.AsIs(lst, stringsAsFactors=FALSE); df 

当转换它看起来像这样(非常接近我想要的):

        lst 
1    a, b, c, d, e, f, g 
2       c, d, e 
3 O, P, Q, R, S, T, U, V, W, X, Y, Z 
4   d, e, f, g, h, i, j, k, l 

在外面看起来不错,当我看着df对象的类时,它说它是一个“data.frame”。但是,当我看到它的结构时,我看到我仍在处理一个列表。

str(df) 

输出:

'data.frame': 4 obs. of 1 variable: 
$ lst:List of 4 
    ..$ : chr "a" "b" "c" "d" ... 
    ..$ : chr "c" "d" "e" 
    ..$ : chr "O" "P" "Q" "R" ... 
    ..$ : chr "d" "e" "f" "g" ... 

我知道一个data.frame是排序列表,但理想的输出为

> str(df) 
'data.frame': 4 obs. of 1 variable: 
$ lst: chr "a,b,c,d,e,f,g" "c,d,e" "O,P,Q,R,S,T,U,V,W,X,Y,Z" "d,e,f,g,h,i,j,k,l" 

我见过非常类似的问题在SO上,但没有一个符合我的期望。 我已尝试以下所有内容,但没有任何工作。任何帮助将不胜感激。

1. mt <- as.matrix(unlist(lst, recursive = FALSE)) 

2. mt <- unlist(lst, recursive = FALSE) 

3. df <- as.data.frame.AsIs(lst, stringsAsFactors=FALSE); df 
    df$nlst <- as.character(rep(NA, nrow(df))) 
    for(inti in 1:length(df)){ 
     df$nlst[inti] <- (df$lst[[inti]]) 
    } 

4. df$nlst <- apply(df, 1, unlist) 

5. df$nlst <- do.call(rbind, df$lst) 

6. df <- as.data.frame(as.matrix(lst)) 

7. df <- plyr::ldply(lst, rbind) 

再次,以上都不符合我的需要。请帮忙!

回答

0

可以pastelist内输出,然后调用data.frame

d1 <- data.frame(Col1=sapply(lst, toString), stringsAsFactors=FALSE) 
str(d1) 
#'data.frame': 4 obs. of 1 variable: 
# $ Col1: chr "a, b, c, d, e, f, g" "c, d, e" "O, P, Q, R, S, T, U, V, W, X, Y, Z" "d, e, f, g, h, i, j, k, l" 
+1

谢谢,akrun!问题解决了!我很感激。 – user3807006

相关问题