I have a list of elements:
E.list <- list("ELP","ARC","DEG","UEG","BAC")
And I want to use them as a variable as well as a pattern in grepl
such as:
ELP <- df[, grepl("ELP", names(df))]
ELP_META <- dplyr::filter(Meta, grepl("ELP", CASE_Name))
ARC <- df[, grepl("ARC", names(df))]
ARC_META <- dplyr::filter(Meta, grepl("ARC", CASE_Name))
.
.
.
How I can do it using for
loop or foreach
?
CodePudding user response:
We may extract the element of the list
with [[
df[, grepl(E.list[[1]], names(df))]
If we need to loop
out <- lapply(E.list, function(nm) {
tmp <- df[, grepl(nm, names(df))]
tmp_META <- dplyr::filter(Meta, grepl(nm, CASE_Name))
return(setNames(list(tmp, tmp_META), c(nm, paste0(nm, "_META"))))
})
In a for
loop we can do
out <- vector('list', length(E.list))
out_META <- vector('list', length(E.list))
names(out) <- E.list
names(out_META) <- paste0(E.list, "_META")
for(nm in E.list) {
out[[nm]] <- df[, grepl(nm, names(df))]
out_META[[paste0(nm, "_META")]] <- dplyr::filter(Meta, grepl(nm, CASE_Name))
}
If the intention is to create multiple objects in the global env, it is not recommended, instead store it in a list
as in the above solutions. But, if we use assign
it would create those objects
for(nm in E.list) {
assign(nm, df[, grepl(nm, names(df))]
assign(paste0(nm, "_META"), dplyr::filter(Meta, grepl(nm, CASE_Name)))
}