Adrian
Adrian

Reputation: 9793

R: How to subset multiple elements from a list

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

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

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

Suppose I had a list x as shown above. I wish to subset the 2nd element of each entry in the list

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

How can I do that in one command? I tried x[[1:3]][2] but I got an error.

Upvotes: 1

Views: 1083

Answers (1)

akrun
akrun

Reputation: 886968

Try

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;"

data

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

Upvotes: 1

Related Questions