Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R list get first item of each element

Tags:

list

r

This should probably be very easy for someone to answer but I have had no success on finding the answer anywhere.

I am trying to return, from a list in R, the first item of each element of the list.

> a
[1] 1 2 3
> b
[1] 11 22 33
> c
[1] 111 222 333
> d <- list(a = a,b = b,c = c)
> d
$a
[1] 1 2 3

$b
[1] 11 22 33

$c
[1] 111 222 333

Based on the construction of my list d above, I want to return a vector with three values:

return  1 11 111
like image 772
gmarais Avatar asked May 25 '17 09:05

gmarais


2 Answers

sapply(d, "[[", 1) should do the trick.

A bit of explanation:

sapply: iterates over the elements in the list
[[: is the subset function. So we are asking sapply to use the subset function on each list element.
1 : is an argument passed to "[["

It turns out that "[" or "[[" can be called in a traditional manner which may help to illustrate the point:

x <- 10:1
"["(x, 3)
 # [1] 8
like image 107
emilliman5 Avatar answered Oct 13 '22 05:10

emilliman5


You can do

 output <- sapply(d, function(x) x[1])

If you don't need the names

 names(output) <- NULL
like image 32
amatsuo_net Avatar answered Oct 13 '22 04:10

amatsuo_net