首先 - 如果以前有人问过这个问题,我很抱歉,我已经看过并且无法找到与我正在尝试做的事情相匹配的任何内容。
我正在尝试创建一个根据数据框中用户生成的列对数据进行分箱的函数。为此,我使用了 dplyr 中的 mutate() 函数和 base R 中的 cut() 函数。但是,我无法弄清楚如何使用通过 cut() 函数内部的函数传递的列名(其中出现在 mutate 中)。
我已经花了几个小时浏览这个和这个,但仍然没有弄清楚。我的理解是下面代码中的 foo()、bar() 和最后一行都应该产生相同的输出。但是,我得到了两个函数错误,一个没有包含在函数中并且只使用硬编码列名的错误可以正常工作。
这里发生了什么?为什么 foo() 产生的输出与 bar() 不同?以及如何正确使用lazyeval 来允许函数中的正确行为?
library(dplyr)
library(lazyeval)
foo <- function(data, col, bins){
by = lazyeval::interp(quote(x), x = as.name(col))
print(paste0("typeof(by): ", typeof(by)))
print(paste0(" by: ", by))
df <- data %>%
dplyr::mutate(bins = cut(by,
breaks = bins,
dig.lab = 5,
include.lowest = T))
df
}
bar <- function(data, col, bins){
df <- data %>%
dplyr::mutate(bins = cut(lazyeval::interp(quote(x), x = as.name(col)),
breaks = bins,
dig.lab = 5,
include.lowest = T))
df
}
#produce sample data and bins list
df <- expand.grid(temp=0:8,precip=seq(0.7,1.3,by=0.1))
df$rel <- seq(40,100,length=63)
bins <- seq(40,100,by=10)
foo(df,"rel",bins) # produces "Error: 'rel' not found"
bar(df,"rel",bins) # produces "Error: 'x' must be numeric"
# but this works
dplyr::mutate(df, bins = cut(rel, breaks = bins, dig.lab = 5, include.lowest = T))