I have a function that works when applied to the dataframes in the global environment, but I'm trying to get it to apply to a list. This question refers back to my previous question here. The function extracts information from the dataframe names in the global environment and makes a new column based on that info, but I would like it to apply to a list of dataframes rather than the dataframes in the global environment. Here's some mock data and the function:
pend4P_17k <- data.frame(x = c(1, 2, 3, 4, 5),
var1 = c('a', 'b', 'c', 'd', 'e'),
var2 = c(1, 1, 0, 0, 1))
pend5P_17k <- data.frame(x = c(1, 2, 3, 4, 5),
var1 = c('a', 'b', 'c', 'd', 'e'),
var2 = c(1, 1, 0, 0, 1))
pend10P_17k <- data.frame(x = c(1, 2, 3, 4, 5),
var1 = c('a', 'b', 'c', 'd', 'e'),
var2 = c(1, 1, 0, 0, 1))
list_pend <- list(pend4P_17k=pend4P_17k, pend5P_17k=pend5P_17k, pend10P_17k=pend10P_17k)
add_name_cols <- function(df){
my_global <- ls(envir = globalenv())
for(i in my_global)
if(class(get(i)) == "data.frame" & grepl("pend", i))
{
df <- get(i)
df$Pendant_ID <- gsub("^pend(.{2,3})_.*$", "\\1", i)
assign(i, df, envir = globalenv())
}
return(df)
}
list_pend <- lapply(list_pend, add_name_cols)
It applies the function to the list, but every dataframe has the same Pendant_ID column, when it should match the ID given in the dataframe name (i.e. the pend4P_17k dataframe should have a Pendant_ID column that is "4P")
Using R version 3.5.1, Mac OS X 10.13.6