[英]R:create new column and value using lapply & apply nested on data.frame list, wrong output
[英]R - transform a list of variable vectors to data.frame with additional column by nested lapply
有一个不同长度的character()
向量list
。 如何有效地将其转换为data.frame
(使用一些Xapply
函数)。 还需要一个额外的ID列。
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)
我的尝试不起作用
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])))
需要输出
> 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
除了最后一个rbind之外,我没有看到你之前的问题有很多不同。 你应该仔细阅读答案。
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.