R:如何从列表中对多个元素进行子集化

时间:2014-11-02 10:39:24

标签: r

    > x
    [[1]]
    [1] "Bob"  "John" "Tom" 
    [2] "Claire" "Betsy"

    [[2]]
    [1] "Strawberry" "Banana"    
    [2] "Kiwi"

    [[3]]
    [1] "Red"
    [2] "Blue" "White"

假设我有一个列表x,如上所示。我希望对列表中每个条目的第二个元素进行子集化

    x[[1]][2]
    x[[2]][2]
    x[[3]][2]

如何在一个命令中执行此操作?我试过了x[[1:3]][2]但是我收到了一个错误。

1 个答案:

答案 0 :(得分:1)

尝试

sapply(x2, `[`,2)
#[1] " from localhost (localhost [127.0.0.1])"                   
#[2] " from phobos [127.0.0.1]"                                  
#[3] " from n20.grp.scd.yahoo.com (n20.grp.scd.yahoo.com"        
#[4] " from [66.218.67.196] by n20.grp.scd.yahoo.com with NNFMP;"

数据

x2 <- list(c("Received", " from localhost (localhost [127.0.0.1])"),
 c("Received", " from phobos [127.0.0.1]"), c("Received", 
 " from n20.grp.scd.yahoo.com (n20.grp.scd.yahoo.com"), 
 c("Received", " from [66.218.67.196] by n20.grp.scd.yahoo.com with NNFMP;" ) )
相关问题