Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

I have a list in R some 10,000 elements long. Say I want to select only elements, 5, 7, and 9. I'm not sure how I would do that without a for loop.

I want to do something like mylist[[c(5,7,9]] but that doesn't work. I've also tried the lapply function but haven't been able to get that working either

1 Answer

0 votes
by
edited by

To select multiple elements from a list, you can use the [ Since [[ returns the element instead of a list.i.e.,

mylist <- list(

  c('A','B','C','D'),

  55:60,

  c(T,F),

  c('A','B','C','D'),

  5:20,

  c(F,F),

  c('A','B','C','D'),

  10:100,

  c(T,T)

)

To get 5th,7th, and 9th element:

> mylist[c(5,7,9)]

[[1]]

 [1]  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

[[2]]

[1] "A" "B" "C" "D"

[[3]]

[1] TRUE TRUE

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...