Apply code to a list of dataframes

I have this code for a individual dataframe

df_MDE <- df_MDE %>% 
  rename("PAIS" = "MS",
         "NPC" = "PARTNER",
         "NC" = "COMM",
         "PAIS_COD" = "COUNTRY",
         "QT_UNID_SUPL" = "QTY_SU")
df_MDE$NC2 <- substr(df_MDE$NC, 1, 2)

I want to apply it to this list of dataframes:

prefix <- "df_MDE_"
VECTOR_MDE <- paste(prefix, VECTOR_ANO_MES, sep = "")

But I get the following error:

Error in UseMethod("rename") : 
  no applicable method for 'rename' applied to an object of class "character"

which states that the list is not a list of dataframes but only a list of four characters.

How can I solve this problem?

If I understand you correctly, you have a list of names of data frames and you want to use that to operate on each data frame. Here is a toy example of doing that using the get() and assign() functions.

#invent two data frames and a vector of their names
DF1 <- data.frame(A = 1:3)
DF2 <- data.frame(A = 2:4)
DFnames <- c("DF1", "DF2")

RenameFunc <- function(Nm) {
  tmp <- get(Nm)
  tmp <- tmp |> rename(B = A)
  assign(Nm, tmp, envir = .GlobalEnv)

walk(DFnames, RenameFunc)

Created on 2023-06-06 with reprex v2.0.2

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.