0

I have two dataset (training dataset and holdout dataset) which have the same variables. How can I specify the variables with same name in two datasets in a function? I tried the following, but it does not work.

function1 <- function (x, y, train, test){
  a<- train$x
  b<- train$y
  c<- test$x
  d<- test$y
 return(list(a,b,c,d))
}
function1(displacement, mpg, train_set, test_set)

The results are NULL for all four. Can anyone tell me how to achieve this?

Teng Li
  • 13
  • 4

1 Answers1

0

Replace $x with [[x]] and see.

function1 <- function (x, y, train, test){
  a<- train[[x]]
  b<- train[[y]]
  c<- test[[x]]
  d<- test[[y]]
 return(list(a,b,c,d))
}
Sonny
  • 3,083
  • 1
  • 11
  • 19
  • to handle NSE (give naked names without `"` to your function) you can do : `x <- as.character(substitute(x))` in your function, same for y, then use `[[` instead of `$` as in this solution – moodymudskipper Mar 02 '19 at 15:22