简体   繁体   English

R - 将变量向量列表转换为data.frame,并使用嵌套lapply附加列

[英]R - transform a list of variable vectors to data.frame with additional column by nested lapply

Have a list of character() vectors of different length. 有一个不同长度的character()向量list How you can transform it into a data.frame efficiently (with some Xapply function). 如何有效地将其转换为data.frame (使用一些Xapply函数)。 Also a additional ID column is required. 还需要一个额外的ID列。

INPUT INPUT

# sentences are like:
sent1 <- "ab"
sent2 <- "bc"
sent3 <- "cd"
sent4 <- "de"

# sections
sec1 <- c(sent1, sent3)
sec2 <- c(sent4, sent3, sent2)
sec3 <- c(sent3)
sec4 <- c(sent2, sent1)

# the whole list
text <- list(sec1, sec2, sec3, sec4)

my try is NOT WORKING 我的尝试不起作用

text2.df <- lapply(text, function(i)
                         lapply(text[[i]], function(j) 
                                           data.frame(ID=paste(sprintf("%02d", i), sprintf("%03d", j), sep = ""), # creates the requred sentence IDs (works properly)
                                                               Sentence=text[[i]][j])))

Requred OUTPUT 需要输出

> text2.df 
     ID Sentences
1 01001        ab
2 01002        cd
3 02001        de
4 02002        cd
5 02003        bc
6 03001        cd
7 04001        bc
8 04002        ab

I don't see a lot of difference with your previous question except the last rbind. 除了最后一个rbind之外,我没有看到你之前的问题有很多不同。 You should carefully read the answers. 你应该仔细阅读答案。

ll <- lapply(seq_along(text),function(i)
  data.frame(ID = paste(sprintf("%02d", i), 
                   sprintf("%03d", seq_along(text[[i]])), 
                   sep = ""),
             sent=text[[i]]))

do.call(rbind,ll) 
     ID sent
1 01001   ab
2 01002   cd
3 02001   de
4 02002   cd
5 02003   bc
6 03001   cd
7 04001   bc
8 04002   ab

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM