edoardo
edoardo

Reputation: 11

How to select items from each vector of the list in R

I would like to select the third item from each vector of the list below. I tried in this way, but I got problems at level 2. I found the function select.list() but I do not know how to apply it. Any suggestions? Many thanks.

newlist =  x[[1:140]][3]
List of 140
chr(0)
chr [1:7] Brachy leaf N11428394 1 
chr [1:7] Brachy leaf N10508942 141 
chr(0) 
chr [1:7] Brachy leaf N35663 5 
chr [1:7] Brachy leaf N12458414 1 
chr [1:7] Brachy leaf N5242558 16 
chr [1:7] Brachy leaf N7738408 1 
chr [1:10] Brachy leaf N9826491 633 

Upvotes: 1

Views: 5216

Answers (3)

Nick
Nick

Reputation: 3384

A more elegant solution to this is using str_split and then map with the integer position.

e.g. using the same list:

x = list('Brachy leaf N11428394 1', 
    'Brachy leaf N10508942 141', 
    'Brachy leaf N356635')

simply use:

x %>% str_split(., " ") %>% map(3)

Upvotes: 0

Gavin Simpson
Gavin Simpson

Reputation: 174948

If I understand the code you show, and x is the list you want to select from, then this will work:

lapply(x, FUN = `[`, 3)

Explanation:

lapply() takes each component of the supplied list and applies a function to it. In effect it is extracting x[[1]] and applying FUN to that, then extracting x[[2]] and applying FUN to it, and so on. So that takes care of this part of your code: x[[1:140]]. You just need to do an extract of the 3 element as the FUN applied. `[` is actually a function in R so we can use it as FUN. It has to be quoted as it is a special name. The final part is to supply arguments to `[`(), which we do here using a unnamed argument (the 3 in the function call shown).

Example:

> x <- list(A = letters[1:7], B = letters[1:7], C = letters[1:7])
> (newlist <- lapply(x, `[`, 3))
$A
[1] "c"

$B
[1] "c"

$C
[1] "c"

> 
> ## or as a vector (not a list) result
> (newlist2 <- sapply(x, `[`, 3))
  A   B   C 
"c" "c" "c"

Upvotes: 7

Ramnath
Ramnath

Reputation: 55735

Here is one way to do it

x = list('Brachy leaf N11428394 1', 
        'Brachy leaf N10508942 141', 
        'Brachy leaf N356635')
sapply(sapply(x, strsplit, split = " "), '[', 3)

This gives

[1] "N11428394" "N10508942" "N356635" 

Upvotes: 5

Related Questions