使R标识什么是data.frame,什么是`……`参数中的列
函数是否可以只包含使R标识什么是data.frame,什么是`……`参数中的列,r,R,函数是否可以只包含…参数,而不管传递给函数的顺序如何,R都可以识别什么是data.frame,什么是列?例如,我不想使用:mean(data$column)而想使用mean(…),其中…可以是(data,column)或(column,data) 我想也许eval可以工作,但还是停了下来。如有任何建议,将不胜感激 f <- function(...) { args <- list(...) x <-eval(substitute(...), ..., parent.fr
…
参数,而不管传递给函数的顺序如何,R都可以识别什么是data.frame,什么是列?例如,我不想使用:mean(data$column)
而想使用mean(…)
,其中…
可以是(data,column)
或(column,data)
我想也许eval
可以工作,但还是停了下来。如有任何建议,将不胜感激
f <- function(...)
{
args <- list(...)
x <-eval(substitute(...), ..., parent.frame())
mean(x)
}
f(women, height)
f(height, women)
f只是为了好玩:
f <- function(...)
{
a <- as.list(match.call())
stopifnot(length(a) == 3L)
x <- a[[2]]
y <- a[[3]]
x <- as.character(x)
y <- as.character(y)
tryCatch(get(x, get(y)),
error = function(e) tryCatch(get(y, get(x)),
error = function(e) {
message("no deal")
NULL
}
)
)
}
f(height, women)
#[1] 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
f(women, height)
#[1] 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
f(women, age)
#no deal
#NULL
f(men, height)
#no deal
#NULL
fFun:)
set.seed(1)
女性:您不能采用数据帧的平均值,最好在…
中使用命名参数。另外,这并没有多大意义,你试图制作一个(非常疯狂的)非标准的求值函数。我建议您阅读并使用lazyeval
软件包。(好吧,我真的建议你不要这样做,但是如果你很固执的话…eval(parse(…)
不是一件有趣的事情,而是一件非常丑陋的事情。)。见106。
set.seed( 1 )
women <- data.frame( height = rnorm( 100, 1.70, 0.1 ) )
f <- function(...){
args <-as.list( match.call( ) )
cmnd_a <- paste0("a <- try(class(",args[[ 2 ]],"), silent = TRUE)" )
a <- eval( parse( text = cmnd_a ) )
if( a == "data.frame" ){
cmnd <- paste0("mean(",args[[2]],"$",args[[3]],")")
}else{
cmnd <- paste0("mean(",args[[3]],"$",args[[2]],")")}
eval( parse( text = cmnd ) )
}
>
> f(height, women)
[1] 1.710889
>
> f(women, height)
[1] 1.710889