Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get access to the first row of a list in R

Tags:

list

r

Consider a list in R, for example

A=list()
A[[1]]=c(1,2)
A[[2]]=c(3,4)

Is it possible to return a vector which gives the first element of each entry of the list (here c(1,3))?

And as a extension: What, if the elements of the list are not just vectors but matrices. Is it possible to get the vector that contains the first element of the second row for each matrix?

like image 528
R_FF92 Avatar asked Jul 18 '16 12:07

R_FF92


2 Answers

 A=list()
 A[[1]]=c(1,2)
 A[[2]]=c(3,4)
 A[[3]]=c(5,6)

 A
 # [[1]]
 # [1] 1 2

 # [[2]]
 # [1] 3 4

 # [[3]]
 # [1] 5 6

I. First Solution using sapply() function for just first elements

 sapply(A,'[[',1)
 # [1] 1 3 5

For Getting lets say 1st, 3rd, 4th elements of each nested list. Not applicable in this example

 sapply(A,`[`,c(1,3,4))

II. Second Solution using for loop

 for(i in 1:length(A)){
 print (A[[i]][1])
 }
 # [1] 1
 # [1] 3
 # [1] 5
like image 118
Sowmya S. Manian Avatar answered Sep 24 '22 08:09

Sowmya S. Manian


Try this below:

sapply(A, "[", 1) 
like image 43
jkt Avatar answered Sep 24 '22 08:09

jkt