Aarn
Aarn

Reputation: 31

Call variable in a function

I get stuck with something that looks fairly easy. From 2 arguments in a function, I'd like to form an existing variable name. Then, I'd like to use the existing variable having this name inside a function (from the package caret). I've some trouble doing this last part.

myfunction <- function(dataset,depvar)
{
First=substitute(dataset) #mydata
Second=substitute(depvar) #Rain
Total=paste(First,Second,sep="$") #"mydata$Rain"
Total=noquote(Total) #mydata$Rain
TrainData <- createDataPartition(y = ????????, p=0.75, list=FALSE)
}

mydata$Rain is the existing variable I'd like to insert instead of the ?????

createDataPartition(y = Total, p=0.75, list=FALSE) #doesn't work
createDataPartition(y = get(Total), p=0.75, list=FALSE) #doesn't work as it indicates object 'mydata$Rain' not found.

Though, mydata$Rain is an existing variable. Any hint?

Upvotes: 0

Views: 43

Answers (1)

MrFlick
MrFlick

Reputation: 206167

Just write your function as

myfunction <- function(dataset,depvar) {
    TrainData <- createDataPartition(y = dataset[[depvar]], p=0.75, list=FALSE)
}

and call it with

myfunction(mydata, "Rain")

Everything is much easier if you just stick to standard evaluation

Upvotes: 1

Related Questions