我正在尝试编写一个使用dplyr来计算z的所有唯一值的函数。当我将变量实际命名为z时,我的函数可以正常工作。但是,如果将变量命名为x,则会出现错误(以下代码)。
test.data<-data.frame(y=c(1:10),
x=c(letters[1:10]))
test.data$x<-as.character(test.data$x)
obsfunction<-function(z,y,data){
filter_(data,
!is.na(deparse(substitute(y))))%>%
distinct_(., deparse(substitute(z)))%>% #the line that breaks it
count_(.)
}
obsfunction(z=x,y,data=test.data)
因此,上面的代码不起作用,并出现此错误:
>Error in eval(substitute(expr), envir, enclos) : unknown column 'z'
在函数中将z更改为x(或将x重命名为z)可以使其工作,但是我不想重命名所有内容,尤其是考虑到y使用不同名称的情况。
我已经尝试了小插图,这个问题和这个问题的lazyeval :: interp和quote()。
distinct_(lazyeval::interp(as.name(z)))%>%
>Error in as.name(z) : object 'x' not found
distinct_(quote(z))%>%
>Error in eval(substitute(expr), envir, enclos) : unknown column 'z'
我想念什么?如何让z接受x作为列名?
由于dplyr标准评估了解字符串,因此我尝试了以下代码,并使用其他测试数据,似乎可以正常工作。我首先提取变量名,然后使用字符串构造表达式:
test.data<-data.frame(y=c(1:10),
x=c(letters[1:10]))
test.data$x<-as.character(test.data$x)
f <- function(z, y, data){
z <- deparse(substitute(z))
y <- deparse(substitute(y))
res <- data %>% filter_(
paste('!is.na(', y, ')', sep = '')) %>%
distinct_(z) %>%
count_(.)
}
x <- f(z = x, y, test.data)
# # A tibble: 1 × 1
# n
# <int>
# 1 10
test.data <- data.frame(
y=c(1:4, NA, NA, 7:10),
x=c(letters[c(1:8, 8, 8)]),
stringsAsFactors = F)
x <- f(z = x, y, test.data)
# # A tibble: 1 × 1
# n
# <int>
# 1 6
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句