R函数参数和环境/命名空间 [英] R function arguments and environments/namespaces

查看:101
本文介绍了R函数参数和环境/命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解R如何处理环境.在 特别是,我想了解如何将数据框传递给 函数,并使用该数据框的命名列作为参数.

I'm having trouble understanding how R handles environments. In particular, I'd like to understand how to pass a dataframe to a function, and use that dataframe's named columns as arguments.

这是一个示例数据框:

DF <- data.frame(pets   = c("puppies", "kitties"),
                 treats = c("kibble", "catnip"))

我可以做到:

paste(DF$pets, "like", DF$treats)

得到一个向量,该向量通知我像粗毛这样的幼犬,以及 猫薄荷之类的小猫.到目前为止,一切都很好.

to get a vector that informs me that puppies like kibble, and kitties like catnip. So far, so good.

我可以将其包装在一个函数中

I can wrap this up in a function:

f <- function(x, y) {
    paste(x, "like", y)
}

这使我可以通过以下任一方式获得相同的输出:

which allows me to get the same output with either:

f(x = DF$pets, y = DF$treats)
with(DF, f(x = pets, y = treats))

那太好了,但我想了解的是 编写一个函数g,这样我就可以使用它:

That's great and all, but what I'd like to understand is how to write a function g such that I can call it with:

g(x = pets, y = treats, data = DF)

g需要什么样?

g <- function(x, y, data = what_do_i_do_here) {
    ## how do I set up the environment so that function g refers
    ## to x and y in the dataframe passed to the data argument?
    paste(x, "like", y)
}

假定xy可能引用数据框中的列 作为data自变量传递给绑定在 全球环境.

Assume that x and y may refer to columns in the dataframe passed as the data argument, or to variables bound in the global environment.

推荐答案

我强烈建议您保持简单,并使用引号引用列.然后您的问题会很快得到解决:

I would strongly recommend you keep it simple and use quotes to reference columns. Then your problem is quickly solved:

g <- function(x, y, df) {
  paste(df[,x], "like", df[,y])
}

# This works
g("pets","treats",DF)
[1] "puppies like kibble" "kitties like catnip"

也可以在不带引号的情况下传递它们,但是此解决方案将成为一种交互式功能,并且您的数据将必须为data.table:

Passing them without quotes is possible too, but then the solution becomes an interactive function, and your data will need to be a data.table:

g2 <- function(x,y,df){
   x <- eval(substitute(x),df, parent.frame())
   y <- eval(substitute(y),df, parent.frame())
   paste(df[,x], "like", df[,y])
}

# This works given DF is a data.table
library(data.table)
DF <- data.table(DF)

g2(pets,treats,DF)
[1] "puppies like kibble" "kitties like catnip"

这篇关于R函数参数和环境/命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆