【发布时间】: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)
【问题讨论】:
-
您应该使用
[或[[对具有变量名称的数据帧进行子集化。不应使用$。见stackoverflow.com/questions/18222286/… -
@RonakShah 评论中的链接是问题的答案,您可能还想看看thisSO post。
-
另见
fortunes::fortune(106)。
标签: r indexing data-manipulation evaluation