I am trying to loop through a list of data frames in the global environment. I want to extract the variable name, substring the variable name, filter (tidyverse) each dataframe, and then save each filtered dataframe. However, I'm having quite a bit of trouble:
query_loop <- function(df){
name <- deparse(substitute(df));
cpt <- paste("cpt_","20", substring(name, 14, 15), sep = "");
assign(cpt, filter(df, CPT == "12345"));
write.table(cpt, file = paste(deparse(substitute(cpt)), ".txt", sep =""), row.names = F, sep = "\t");
}
dfs1 <- lapply(dfs, query_loop)
The code fails at the first step of my function. When I try to print(deparse(substitute(df)))
, I get a list of X[[i]], which I understand is because the dataframes are not named when I pass them to lapply. However, I don't know what the correct solution is.
Any help would be greatly appreciated. Thanks!