我正在尝试构建一个函数,在该函数中我将数据帧作为输入,并在该数据帧中作为两个变量。例如:
mydf <- data.frame(var_a = runif(10),
var_b = runif(10))
my_fun <- function(df, var1, var2){
output <- (df$var1 - df$var2) / df$var2
return(output)
}
my_fun(mydf, var_a, var_b)
Warning messages:
1: Unknown column 'var1'
2: Unknown column 'var2'
3: Unknown column 'var2'
我做错了什么?
编辑:尝试各种其他方式:
my_fun <- function(df, var1, var2){
output <- (df[var1] - df[var2]) / df[var2]
return(output)
}
my_fun(mydf, var_a, var_b)
Error in `[.data.frame`(df, var1) : object 'var_a' not found
my_fun <- function(df, var1, var2){
output <- (df[[var1]] - df[[var2]]) / df[[var2]]
return(output)
}
my_fun(mydf, var_a, var_b)
Error in `[.data.frame`(df, var1) : object 'var_a' not found
Edit2:带引号:
my_fun <- function(df, var1, var2){
output <- (df[["var1"]] - df[["var2"]]) / df[["var2"]]
return(output)
}
my_fun(mydf, var_a, var_b)
numeric(0)
my_fun <- function(df, var1, var2){
output <- (df["var1"] - df["var2"]) / df["var2"]
return(output)
}
my_fun(mydf, var_a, var_b)
Error in `[.data.frame`(df, "var1") : undefined columns selected