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_))

以下のように、最初の 3 つと最後の 3 つのリストを組み合わせて、それぞれ 4 つのベクトルの 2 つのリストを取得したいと考えています (これは最初のリストのみです)。

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

これは、あなたが与えた出力にかなり近いです。違いは、すべての単語が入力に持つ先頭のスペースを削除しなかったことです。先頭のスペースを削除すると、結果の 2 番目の要素に "strategy" と "strategy" の両方が含まれなくなります。

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 に答える