在ggplot中,我们可以很容易地在代码中放入数据帧的变量名,即
df <- data.frame(a=1:10, b= 1:10, c= 1:10)
ggplot(df, aes(a, b, col= c)) + geom_point()
或者我们可以在代码内部转换变量,即在这里我们将颜色变量c
更改为一个因子:
ggplot(df, aes(a, b, col= as.factor(c))) + geom_point()
我希望我的函数也这样做。所以如果我的功能是
my_fun <- function(data, var){
var <- deparse(substitute(var))
class(data[ , var])
}
我希望my_fun(df, a)
返回numeric
,另一方面,my_fun(df, as.factor(a))
必须返回factor
。我们如何才能做到这一点?
试试这些。
my_fun1 <- function(data, x) eval(substitute(x), data)
my_fun2 <- function(data, ...) with(data, ...)
my_fun3 <- with
例如(其他类似(
my_fun1(BOD, Time) # returns numeric object
## [1] 1 2 3 4 5 7
my_fun1(BOD, factor(Time)) # returns factor object
## [1] 1 2 3 4 5 7
## Levels: 1 2 3 4 5 7