【发布时间】:2010-11-04 12:50:47
【问题描述】:
我想知道如何将某个函数的参数传递给与 / 一起使用的函数的子部分。例如:
myfunction <- function(dataframe,col1,col2){
res <- within(dataframe, somenewcol <-paste(col1,"-","col2",sep=""))
return(res)
}
其中 col1 和 col2 是数据框中包含的列。将参数 col1 和 col2 传递给 inside 表达式的正确方法是什么?当我尝试使用它时,我得到:
粘贴错误(col1, "-", , : 找不到对象“Some_passed_col”
这是一个例子:
dataset <- data.frame(rnorm(20),2001:2020,rep(1:10,2))
names(dataset) <- c("mydata","col1","col2")
myfunction <- function(dataframe,arg1,arg2){
res <- with(dataframe, onesinglecol <- paste(arg1,"-","arg2",sep=""))
return(res)
}
# call function
myfunction(dataset,col1,col2)
编辑:
the following works for me now, but I cannot completely understand why... so any further explanation is appreciated:
myfunction(dataset,arg1="col1",arg2="col2")
如果我调整
res <- with(dataframe, onesinglecol <- paste(get(arg1),"-",get(arg2),sep=""))
【问题讨论】:
-
请完成模型示例。
-
@Dirk Eddelbuettel,谢谢提醒,给你...
-
不可重现。我们需要一个模拟数据集和一个模拟函数。
-
好吧,我没有设置种子,但除此之外,前两行生成了一个适合测试这个的数据集..
标签: r