0

I have a list containing j objects. Lets call this list as X. Each object contains k items. I can access particular value(lets say 2'nd item) of an object(lets say 3'rd object) using below method.

X[[3]][2]

How do I access a list containing all the 2'nd items of each objects?

itthrill
  • 1,241
  • 2
  • 17
  • 36
  • `lapply(X, function(x) x[2])` output a list containing the second items of the objects (in X). – raymkchow Apr 18 '18 at 15:15
  • I think you should modify the questions first, because there should be possibly duplicated questions for such kind of "extract list of list of list" questions. [see this](https://stackoverflow.com/questions/23758858/how-can-i-extract-elements-from-lists-of-lists-in-r) – raymkchow Apr 18 '18 at 15:22
  • thanks @raymkchow. Your suggestion works well. As suggested by others I will use sapply to get a simple list. – itthrill Apr 18 '18 at 15:28

2 Answers2

0

Try

 all <- list(a=c(1,2),b=c(2,3))
 lapply(all, `[[`, 2)

 $a
 [1] 2

 $b
 [1] 3
A. Suliman
  • 12,923
  • 5
  • 24
  • 37
  • lapply(X, `[[`, 2) [[1]] [1] 0.008048156 [[2]] [1] 0.007682355 [[3]] [1] 0.009694033 [[4]] [1] 0.00733318 [[5]] [1] 0.009694033 [[6]] [1] 0.008048156 [[7]] [1] 0.0310138 [[8]] [1] 0.0116765 [[9]] [1] 0.006999876 [[10]] [1] 0.008832842 Is it possible to get something like this: (0.008048156,0.007682355.....) – itthrill Apr 18 '18 at 15:22
  • 1
    @itthrill Yes, it is. Just use `sapply(all, `[[`, 2)`. (The `s` in `sapply` means to **s**implify the output if possible.) – Rui Barradas Apr 18 '18 at 15:24
  • 1
    Maybe you could add the `sapply` version to your answer. – Rui Barradas Apr 18 '18 at 15:25
  • I hope it help, dput(unlist(lapply(all, `[[`, 2),use.names = F)) Output: c(2, 3) – A. Suliman Apr 18 '18 at 15:28
0
df <- as.data.frame(unlist(lapply(X, function(x) x[2])))
df
conv3d
  • 2,668
  • 6
  • 25
  • 45