Home > Software engineering >  Create R function
Create R function

Time:03-24

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]

CodePudding user response:

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)
  • Related