1

一旦列表开始变得有点嵌套,我就会更加努力地与它们斗争(我认为其他人也可能会为嵌套列表而斗争)。我有一个列表,我想以某种格式放在一起。这是列表的示例:

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"))
4

2 回答 2

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"

请注意,它与您给出的预期输出不完全匹配。也许您可以帮助澄清这些差异?

于 2012-07-08T13:25:12.570 回答
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"
于 2012-07-08T13:33:22.353 回答