2016-10-19 59 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

相關問題