【问题标题】:Convert a list of character vectors of various length to a one column data.frame in R将各种长度的字符向量列表转换为 R 中的单列 data.frame
【发布时间】:2017-02-28 13:34:02
【问题描述】:

我有一个包含 400,000 个不同长度的字符向量的列表,我想将此列表转换为单列 data.frame,每一行都是从原始字符向量连接的字符串。

这是一个例子。

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)

再一次,以上都不能满足我的需求。请帮忙!

【问题讨论】:

    标签: r


    【解决方案1】:

    你可以在list内输出paste然后调用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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 2018-10-14
      • 2011-10-27
      相关资源
      最近更新 更多