1
votes

I have a list as bellow:

A<-list(10:20,35:45,70:80,45:39,86:120)

I want to make a vector from this list that the elements of the vector are the second element of each item of the list. Indeed I want to make the vector (11,36,71,44,87) using a function of apply-family. My question is which of the functions of apply-family (i.e., apply, sapply, tapply, lapply) is better for this situation and how?

I also want to find the sum of each item of the above list. I know that I can easily use sum function separately for each item like sum(10:20), sum(35:45), sum(70:80) and so on, but how can I do it in a shorter way?

1

1 Answers

2
votes

We can loop over the list and extract the second element

sapply(A, `[`, 2)
#[1] 11 36 71 44 87

If we want to find the sum

sapply(A, sum)
#[1]  165  440  825  294 3605