R 如何将变量通过带引号的表达式传递到使用该值返回函数的函数中?
下面是一个例子:R 如何将变量通过带引号的表达式传递到使用该值返回函数的函数中?,r,ggplot2,tidyverse,tidyeval,non-standard-evaluation,R,Ggplot2,Tidyverse,Tidyeval,Non Standard Evaluation,下面是一个例子: library(ggplot2) library(scales) # for percent() function custom_percent <- function(n){ function(x){ return(paste(percent(x), sprintf('(%d)', round(x* (n))))) } } mydata = data.frame(x = rep(c('a','b','c'), each=100))
library(ggplot2)
library(scales) # for percent() function
custom_percent <- function(n){
function(x){
return(paste(percent(x), sprintf('(%d)', round(x* (n)))))
}
}
mydata = data.frame(x = rep(c('a','b','c'), each=100))
ggplot(mydata) + geom_text(aes_(x=~x, y=~..prop..,
label=bquote(.(custom_percent)(length(x))(..prop..)),
stat='count')
但是当我这样做的时候,我得到了一个错误:error in!n:参数类型无效
有人知道如何在custom_percent()
返回的函数中正确使用所需的n
值吗
在任何人询问之前,我知道我可以预先在摘要数据框中生成统计信息,或者使用
utils::getAnywhere()
作为解决方法,但这不是问题的重点。您可以使用基r替换
捕获整个表达式,然后将表达式编写为函数体
custom_percent <- function(n){
n=eval(n)
m=substitute(return(paste(percent(x), sprintf('(%d)', round(x*n)))))
`functionBody<-`(function(x)1,parent.frame(),m)
}
s=3
custom_percent(s)
function (x)
return(paste(percent(x), sprintf("(%d)", round(x * 3))))
custom\u percent问题不在于您的函数-它看起来和最初编写的一样好。geom_文本调用中缺少括号,我认为这是主要问题
custom_percent <- function(n){
function(x){
return(paste(percent(x), sprintf('(%d)', round(x* (n)))))
}
}
# I made the data slightly more variable
mydata = data.frame(x = rep(c('a','b','c'), rbinom(3, 100, .8)))
ggplot(mydata, aes(x = x)) +
# geom_bar(stat = 'count') +
geom_text(aes_(label=bquote(.(custom_percent)(length(x))(..count.. / sum(..count..)))),
stat='count')
您需要什么作为输出?例如,自定义百分比(3)
输出应该是什么?您使用的是什么版本的ggplot2
?我正在使用dev版本,并在FUN(X[[I]],…)中获得错误:未知输入:函数
注意,您只能使用代码>在tidy eval函数的参数中paste()
、sprintf()
和round()
都是正常功能。
custom_percent <- function(n){
function(x){
return(paste(percent(x), sprintf('(%d)', round(x* (n)))))
}
}
# I made the data slightly more variable
mydata = data.frame(x = rep(c('a','b','c'), rbinom(3, 100, .8)))
ggplot(mydata, aes(x = x)) +
# geom_bar(stat = 'count') +
geom_text(aes_(label=bquote(.(custom_percent)(length(x))(..count.. / sum(..count..)))),
stat='count')
ggplot(mydata, aes(x = x, y = ..prop..), stat = 'count') +
# geom_bar(aes(y = ..prop..), stat = 'count') +
geom_text(aes_(label=bquote(.(custom_percent)(length(x))((..count..) / sum(..count..)))),
stat='count') +
scale_y_continuous(labels=scales::percent)