1

I'm new to R, trying to understand how to access elements of my dataframe when I add them to a list.

I can access the elements of the dataframe normally but can't do the same when I add the dataframe to the list. How can I do it? Thanks

abc <- rbind(presence[2,], presence[6,], presence[9,])
bca <- rbind(presence[5,], presence[7,], presence[10,])
cab <- rbind(presence[4,], presence[8,], presence[12,])

abc[1,7] #works

sets <- list(abc, bca, cab)
sets$abc[1,7] #returns NULL
SF1
  • 469
  • 1
  • 6
  • 20
  • 2
    Your list elements don't have names. You can access them by index: `sets[[1]][1, 7]` or give them names as akrun suggests. – lmo Jan 26 '20 at 18:25
  • You may also benefit from reading [this SO post](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) on creating a list of data.frames. My answer there shows how the `mget` function can be used to construct named lists of objects when there names follow some pattern. – lmo Jan 26 '20 at 18:33

1 Answers1

2

There is no

sets$abc

as the list is unnamed

We need to name it

names(sets) <- c('abc', 'bca', 'cab')

Or when creating the list use

sets <- list(abc = abc, bca = bca, cab = cab)

With purrr, the naming is automatically done with lst

sets <- purrr::lst(abc, bca, cab)

Or use dplyr::lst

sets <-  dplyr::lst(abc, bca, cba)

Instead of extracting each element one by one, this can be also done with lapply/sapply

lapply(sets, `[`, 1, 7)

Or with sapply to return a vector

sapply(sets, `[`, 1, 7)
akrun
  • 874,273
  • 37
  • 540
  • 662