【问题标题】:R: How to subset multiple elements from a listR:如何从列表中子集多个元素
【发布时间】:2014-11-02 10:39:23
【问题描述】:
    > 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],但出现错误。

【问题讨论】:

  • dput(x) 将不胜感激
  • @Adrian 不清楚子元素是如何存储在每个列表元素中的。
  • 抱歉,我不知道如何重新创建x。
  • 看到我上面的评论了吗?
  • @Adrian 您的预期结果是什么?是John,Banana,Blue

标签: r


【解决方案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;" ) )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2015-01-04
    相关资源
    最近更新 更多