![](/img/trans.png)
[英]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.