0

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!

aynber
  • 22,380
  • 8
  • 50
  • 63

1 Answers1

3

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)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • This is already a step forward, thanks! I was wondering whether there is a way to actively change the column names of the dataframe within the function? So for example: instead of getting the input of the X argument (here: "var1"), how can I change the name of "var1" into "X" within the function? And not only for this particular dataframe, but for whatever dataframe that's used in the function? –  Sep 06 '21 at 11:17
  • Do you mean to change the column name of "var1" to "X" ? Maybe `names(data)[match(X, names(data))] <- 'X'` but I am not sure if that makes sense. – Ronak Shah Sep 06 '21 at 12:22
  • This is exactly what I was looking for, a massive thank you! –  Sep 06 '21 at 14:31