I'm trying to create multiple data frames within a list within another list from one original data base using two for loops.
The first iteration applies a for loop to de original data base that uses the levels of the factor as index to group data by sites, creating a sites list.
The second iteration (the one i'm having problems), I wan't it to create data frames within the sites lists that are grouped by year.
set.seed(100)
N <- sample(50, 100, replace = TRUE)
Year <- as.factor(sample(rep(2011:2020, each = 5)))
Site <- as.factor(sample(rep(c('S1', 'S2', 'S3', 'S4', 'S5'), each = 10)))
Species <- sample(rep(c('spp1', 'spp2', 'spp3', 'spp4', 'spp5'), each = 10))
DataBase <- data.frame(Year, Site, Species, N)
Ind <- list()
Ind_year <- list ()
for (i in levels(DataBase$Site)) {
Ind[[i]] <- DataBase %>%
filter (Site == as.character(i)) %>%
group_by(Year, Species) %>%
count() %>%
droplevels()
for(j in levels(Ind[[(i)]]$Year)) {
Ind_year[[j]] <- as.data.frame(Ind[[i]] %>%
filter (Year == as.character(j)) %>%
group_by(Year, Species) %>%
droplevels())
}
}
No error detected, but the result within the first list is this: Site 1 Site 2 Site 3 . . . Year 1 Year 2 Year 3
For example, I want the Site 1 list within the Ind list to contain the data frames of Year 1...Year n.
Any help would be appreciated.