user16841962
user16841962

Reputation:

How to rename a column of a dataframe within a function in R?

I am trying to write a function in R, but I'm struggling on how to get the input of the arguments of the function and how to change it within the function itself.

For example:

# Create dataframe
df <- data.frame(1:10, 1:10, 1:10, 1:10)
colnames(df) <- c("var1", "var2", "var3", "var4")

# Create function
myfunction<-function(X, Y, M=c(...), data){
print(X)
print(Y)
print(M)
}

# Test function
myfunction(df$var1, df$var2, c(df$var3, df$var4), df)

Now I want to rename the input of the X argument to "X", the input of the Y argument to "Y" and the input vector of M to "M" (first element) and "M2" (second element).

More concretely: "var1" should get the name "X" "var2" should get the name "Y" "var3" should get the name "M1" "var4" should get the name "M2"

How can I do this? Ofcourse I can rename the column names of the dataframe itself upfront, but the main cause of the function is that with whatever dataframe and whatever column names you put into the arguments, the input of those arguments should be recoded to "X", "Y", "M1" and "M2".

Any ideas? Thanks a lot!

Upvotes: 0

Views: 1035

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389055

Pass the column names as string if you want to use them. It is not possible to get "var1" value if you pass df$var1 as input to the function. You can use [[ (and [) to subset the data from column names in the function.

myfunction<-function(X, Y, M=c(...), data){
  print(X)
  print(Y)
  print(M)
  val1 <- data[[X]]
  val2 <- data[[Y]]
  val3 <- data[M]
}

# Test function
myfunction("var1", "var2", c("var3", "var4"), df)

Upvotes: 3

Related Questions