I have a list (gro
) of groups ('gg', 'gm', 'gp', 'mg', 'mm', 'mp', 'pg', 'pm', 'pp') which tells me which species are in which groups. I also have a list of data frames (before
) with the data for each species.
I want to take dataframes from before
and create new lists named for each group. I have been doing this with nested ifelse statements, but this is very ugly and convoluted:
gg_pow <- list()
gm_pow <- list()
gp_pow <- list()
mg_pow <- list()
mm_pow <- list()
mp_pow <- list()
pg_pow <- list()
pm_pow <- list()
pp_pow <- list()
for (i in 1:length(before)){
df <- before[[i]]
ifelse(df$species[1] %in% paste0(gro[['gg']]$species),
gg_pow[[paste(df$species[1])]] <- df,
ifelse(df$species[1] %in% paste0(gro[['gm']]$species),
gm_pow[[paste(df$species[1])]] <- df,
ifelse(df$species[1] %in% paste0(gro[['gp']]$species),
gp_pow[[paste(df$species[1])]] <- df,
ifelse(df$species[1] %in% paste0(gro[['mg']]$species),
mg_pow[[paste(df$species[1])]] <- df,
ifelse(df$species[1] %in% paste0(gro[['mm']]$species),
mm_pow[[paste(df$species[1])]] <- df,
ifelse(df$species[1] %in% paste0(gro[['mp']]$species),
mp_pow[[paste(df$species[1])]] <- df,
ifelse(df$species[1] %in% paste0(gro[['pg']]$species),
pg_pow[[paste(df$species[1])]] <- df,
ifelse(df$species[1] %in% paste0(gro[['pm']]$species),
pm_pow[[paste(df$species[1])]] <- df,
pp_pow[[paste(df$species[1])]] <- df
)
)
)
)
)
)
)
)
}
I am trying to improve my coding in general and I know I should be able to use lapply
to acheive this, but I don't know how best to structure the function to apply to each element in before
.
Any help in how to condense this all down would be greatly appreciated.