【问题标题】:R: how to index by $ instead of [] in a function?R:如何在函数中按 $ 而不是 [] 进行索引?
【发布时间】:2021-02-11 07:21:42
【问题描述】:

我正在写一个R函数,它以一个数据框和变量名作为输入,对输入变量名对应的数据框中的向量进行一些操作,然后返回结果向量。

虽然我可以使用[] 编写此函数来索引,但我正在尝试学习如何使用$ 来索引(我知道这可能是个坏主意)。

我最好的猜测是我需要将我想要的字符串粘贴在一起,并以某种方式使用parse()eval()substitute() 或其他一些函数,但我怀疑可能有更好的方法。任何帮助表示赞赏。

# Create an arbitrary data frame
df <- data.frame(x = c("a","b","c","c","c"),
                 y = 1:5,
                 z = c(1,9,NA,0,NA))

# Create a vector with character "y",
# capturing the name of the column
# I want to work with in my data
M <- "y"

# Write a function that takes a 
# data frame and a variable name,
# adds 5 to each value of that 
# variable in the data frame, then
# prints the resulting numeric vector.
# Below produces the desired output
# of the function:
print(df$y + 5)

#####################################
# Define function to add 5 to a specified
# variable in the data frame using [] indexing
fun1 <- function(dat, var) {
    df[ ,var] + 5
}

# Works with both quoted values and
# objects assigned quoted values
fun1(dat = df, var = "y")
fun1(dat = df, var = M)

# However, doesn't work when I use 
# $ instead of []. See function below
# and corresponding results.
fun2 <- function(dat, var) {
  df$var + 5
}

# Doesn't produce intended result
fun2(dat = df, var = "y")
fun2(dat = df, var = M)

【问题讨论】:

标签: r indexing data-manipulation evaluation


【解决方案1】:

你可以这样做。你真的不应该,但你可以。

与 R 中的所有运算符一样,$ 实际上是一个函数。它的第一个参数是一个列表(可能但不一定是 data.frame 类),第二个参数是一个名称(“符号”类型的对象)。由于$ 不计算第二个参数,因此如果您打算以编程方式传递它,则需要替换它。

我会这样做:

fun2 <- function(dat, var) {
  var <- as.name(var)
  eval(substitute("$"(dat, var) + 5))
  }

fun2(dat = df, var = "y")
#[1]  6  7  8  9 10
fun2(dat = df, var = M)
#[1]  6  7  8  9 10

如果您像 R 开发人员预期的那样使用 [,看看这有多好?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-20
    • 2015-11-04
    • 2018-11-18
    • 2021-09-09
    • 2011-11-26
    • 2019-10-17
    • 1970-01-01
    • 2016-07-12
    相关资源
    最近更新 更多