Reputation: 2072
I have .RData files stored and I would like to do a function that load the .RData and then use a data.frame named df that was in the .RData, but the name of the data.frame is a parameter of the function, like this:
test <-function(rdat,df)
{
load(rdat)
df <-with(df, subset(df, status=='A'))
test1(df)
}
test1 <-function(df)
{
df$new <- mean(df$old)
}
I don't realize how to convert a string with the name of a data.frame in a data.frame object to use, I can't pass the data.frame itself because it doesn't exist. Maybe there is a way to search in the environment for the data.frame named df.
Thanks!
Upvotes: 1
Views: 2269
Reputation: 37889
You need to use the get
function:
As an example of how get
works try this:
mat <- matrix(letters, ncol=2)
get('mat')
# [,1] [,2]
#[1,] "a" "n"
#[2,] "b" "o"
#[3,] "c" "p"
#[4,] "d" "q"
#[5,] "e" "r"
#...and so on
So your function could be like this:
test <-function(rdat,df)
{
load(rdat)
#get will give you the data.frame from a string
df <- get(df)
#also you do not need 'with' with subset because subset uses NSE anyway
#and also using subset inside of functions is error prone because of NSE
#use simple subsetting which is faster, too
df <- df[df$status=='A',]
test1(df)
}
Upvotes: 2