Theoden
Theoden

Reputation: 297

How to access the contens of a list using a vector of names in R?

I have a list such as X, which contains certain entries X$(y1,...), the name of the entries are saved in a char vector named Y. Now I want to use mapply to access the contents of X$Y. I write the following mapply line:

aux<-mapply(function(x,y) x$y$family ,X,Y)

The objective being able to access the content "familly" without writing a loop. I receive the following error

Error in x$y$family : $ operator is invalid for atomic vectors

Where am I making the error?

For example:

 X<-list(x1=c(1,2),y1=c(3,4))
 Y<-c("x1","y1")
 aux<-mapply(function(x,y) x$y[[1]],X,Y)

I should like aux to be c(1,3)

Upvotes: 0

Views: 64

Answers (1)

akrun
akrun

Reputation: 887221

Use the names vector ("Y") to subset the elements of "X" i.e. X[Y], loop through those with sapply and extract the first element from each of the vector in the list.

unname(sapply(X[Y], `[`, 1))
#[1] 1 3

If the "Y" vector contains all the names of the "X" element, there is no need to use X[Y] (as @Frank mentioned), just directly loop over the "X" and get the first element

unname(sapply(X, `[`, 1))

Upvotes: 1

Related Questions