一旦列表开始有点嵌套,我就会与它们进行更多的斗争(我认为其他人也可能会遇到嵌套列表)。我有一个列表,我希望以某种格式放在一起。以下是列表的示例:
ms2 <- list(list(" question", c(" thin", " thick"), " one", c(" simple",
" big")), list(" infer", " theme", c(" strategy", " guess", " inform"
), c(" big", " idea", " feel", " one")), list(
"synthesi", c(" predict", " thin", " thick", " parts", " visual",
" determin", " schema", " connect", " background", " knowledge",
" strategy", " infer", " question", " importance"), NA_character_,
c(" things", " picture")), list(" visual", " strategy", " picture",
NA_character_), list(" question", " wonder", c(" them", " one"
), NA_character_), list(" predict", NA_character_, c(" think",
" guess", " wonder"), NA_character_))
我想将前三个和最后三个列表组合在一起,得到2个4个向量的列表,如下所示(这只是第一个列表)。
list(c("question", "infer", "synthesi", "visual"),
c("thin", "thick", "theme", "predict", "parts",
"visual", "determin", "schema", "connect", "backgraound",
"knowledge", "strategy", "infer", "question", "importance",
"strategy"),
c("one", "strategy", "guess", "inform", "picture"),
c("simple", "big", "idea", "feel", "one", "things", "picture"))
答案 0 :(得分:3)
这样的事情:
slice.it <- function(i,x) {
slice <- lapply(x, `[[`, i)
words <- unlist(slice)
words <- words[!is.na(words)]
}
lapply(1:4, slice.it, ms2[1:3])
# [[1]]
# [1] " question" " infer" "synthesi"
# [[2]]
# [1] " thin" " thick" " theme" " predict" " thin"
# [6] " thick" " parts" " visual" " determin" " schema"
# [11] " connect" " background" " knowledge" " strategy" " infer"
# [16] " question" " importance"
# [[3]]
# [1] " one" " strategy" " guess" " inform"
# [[4]]
# [1] " simple" " big" " big" " idea" " feel" " one" " things"
# [8] " picture"
请注意,它与您提供的预期输出不完全匹配。也许你可以帮助澄清这些差异?
答案 1 :(得分:3)
这非常接近您提供的输出。不同之处在于我没有删除输入中所有单词所具有的前导空格。如果删除前导空格,则结果的第二个元素中不会同时包含“策略”和“策略”
lapply(1:4, function(i) {
unique(na.omit(unlist(lapply(ms2, "[", i)[1:4])))
})
#[[1]]
#[1] " question" " infer" "synthesi" " visual"
#
#[[2]]
#[1] " thin" " thick" " theme" " predict" " parts"
#[6] " visual" " determin" " schema" " connect" " background"
#[11] " knowledge" " strategy" " infer" " question" " importance"
#
#[[3]]
#[1] " one" " strategy" " guess" " inform" " picture"
#
#[[4]]
#[1] " simple" " big" " idea" " feel" " one" " things" " picture"