在R中如何将数据框列名传递给函数

时间:2015-03-23 10:09:52

标签: r function ggplot2 dataframe

我试图将数据帧列名称传递给函数,以便可以将相同的名称传递给ggplot函数。我试图将名称作为字符串传递,然后转换为变量名称。这些方法都不起作用。以下是我试图做的一个例子。

#
# Trying to use the variable directly
my.f <- function(var1, var2, data=NULL) {
  p <- ggplot(data, aes(var1, var2))
  p + geom_boxplot(outlier.colour = "green", outlier.size = 3)
}

# Retrieve the variable from the parent.frame.
my1.f <- function(var1, var2, data=NULL) {
  var <- as.list(match.call()[-1])
  p <- ggplot(data, aes(var$var1, var$var2))
  p + geom_boxplot(outlier.colour = "green", outlier.size = 3)  

  # Create a new datafram. I can create a new data frame
  # but, ggplot doesn't access those names still as only way to 
  # get variables names is as demonstrated above.
  v1 <- deparse(substitute(var1))
  v2 <- deparse(substitute(var2))
  p.df <- data[, c(v1, v2)]
  print(names(p.df))
  p <- ggplot(p.df, aes(var$var1, var$var2))
  p + geom_boxplot(outlier.colour = "green", outlier.size = 3)  
}

#
# Create a simple data frame.  The type is not significant
# as the objective is to show how to pass column names to a
# function
a <- runif(20)
b <- runif(20)
c <- runif(20)
my.df <- data.frame(a, b, c)

# my.f tries to use the variable name directly
my.f(a, b, my.df)

# my1.f retrieves the variable names from the parent.frame.
my1.f(a, b, my.df)

my.fmy1.f都会返回错误

> my.f(a, b, my.df)
Error in eval(expr, envir, enclos) : object 'var1' not found
> my1.f(a, b, my.df)
[1] "a" "b"
Error in var$var1 : object of type 'closure' is not subsettable

总之,我试图将data.frame列名传递给一个函数,该函数又将名称传递给其他内部函数(例如.ggplot)。感谢您的帮助。

0 个答案:

没有答案