0

I am new to R, and I am not really sure how to phrase the title of the question. I am trying to make a script that I can use on different dataframes, only changing the name of the testing variable. For instance, if I have one dataframe (df) with training data train.data with X Y Z variables and I want to test on X, i.e.

testSVM.model<-svm(df$X ~ ., data =train.data)

Then I have another set of data that I want to use the same script on but the dataframe has the structure I J K L and I want to test on J, i.e.

testSVM.model<-svm(df$J ~ ., data =train.data)

instead of writing 2 different scripts, I would like to assign the variable of interest to a variable such as variable.test, which would just need assignment before running the script.

I have tried setting this variable to a constant

variable.test<-'X'

and use

testSVM.model<-svm(df$'variable.test' ~ ., data =train.data)

but this gives an error, so not correct.

I have also tried, but know this is incorrect, to set the variable to the df data

variable.test<-df$X

and use

testSVM.model<-svm(variable.test ~ ., data =train.data)

Again, I am not sure how to properly phrase the question for the header, and I have done about 2 hours of SO searching and Google, but to no avail.

mkunkel
  • 243
  • 3
  • 16
  • It's not a variable you need but to wrap your code as a function. As in other languages, functions allow you to generalise what you supply as their arguments so you can apply the same function without rewriting it for different input variables. You'll need to read up on R functions. – Stewart Ross Jan 15 '18 at 16:44
  • True, I can use a function, but in other languages I can assign a variable as pass it. For instance in Java I can create an object that can parse the input of the constructor to the variable desired. Is this not possible in R? – mkunkel Jan 15 '18 at 16:51
  • You can't use `$` with a variable. You can use `[[` though. Or if it's really about just building a formula, you can do that with `reformulate()`. – MrFlick Jan 15 '18 at 17:06

0 Answers0