Reputation: 469
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
Upvotes: 1
Views: 74
Reputation: 887118
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)
Upvotes: 2