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!
names(dfs)is a character vector, sodfin your function is a length-1 character vector with the name of the current data frame. Normally one usesdeparse(substitute())to get a string--you already have a string.names(df)return the names of data frames in your global environment? If you already have the names of all the data frames, you can usemgetto obtain all those data frames in a listdfsinto lapply, which is a list of the dataframes. The rest of my question is correct, i.e. when I try to print(deparse(substitute(df))), it prints out X[[i]] 6 times (the number of dataframes in the list)listnamed? If so, use the names of the list as your code shows. If not, name the list and use the names of the list as your code shows.