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?
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
Try this below:
sapply(A, "[", 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With