简体   繁体   English

将data.frame名称传递给函数R

[英]pass data.frame name to a function R

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: 我已经存储了.RData文件,我想做一个加载.RData然后使用.RData中名为df的data.frame的函数,但是data.frame的名称是该函数的参数,像这样:

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. 我不知道如何在要使用的data.frame对象中转换带有data.frame名称的字符串,我无法传递data.frame本身,因为它不存在。 Maybe there is a way to search in the environment for the data.frame named df. 也许有一种方法可以在环境中搜索名为df的data.frame。

Thanks! 谢谢!

You need to use the get function: 您需要使用get函数:

As an example of how get works try this: 作为如何get工作的示例,请尝试以下操作:

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM