[SOLVED] Create R function

Issue

could you help me to convert all these code in a single function? I need to avoid writing code for every single dataframe

data <- merge(x = data_2021, y = corr_df, by = "XCode", all.x = TRUE)

#Drop column
data = subset(data, select = -c(XCode))

# Rename columns
names(data)[names(data) == "Zvar"] <- "XCode"

# Reorder column by name
col_order <- c("XCode", "x2" , "x3")
data <- data[,col_order]

Solution

Maybe something like this:

fn <- function(x,y) {
  data <- merge(x = x, y = y, by = "XCode", all.x = TRUE)

  ## Drop column
  data = subset(data, select = -c(XCode))

  ## Rename columns
  names(data)[names(data) == "Zvar"] <- "XCode"

  ## Reorder column by name
  col_order <- c("XCode", "x2" , "x3")
  data <- data[,col_order]
  data
}

data <- fn(data_2021, corr_df)

Answered By – Stefano Barbi

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.