我想在函数中使用变量名作为字符串dplyr.请参阅以下示例:
df <- data.frame(
color = c("blue", "black", "blue", "blue", "black"),
value = 1:5)
filter(df, color == "blue")
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但我想color通过字符串来引用,类似这样:
var <- "color"
filter(df, this_probably_should_be_a_function(var) == "blue").
Run Code Online (Sandbox Code Playgroud)
我很高兴,无论如何都要这样做,并且非常乐意使用易于阅读的dplyr语法.
dplyr 0.7的发布包括对dplyr 进行编程的重大改进.我仔细阅读了本文档,并试图了解它对我使用dplyr的影响.
这是我在使用dplyr构建报告和聚合函数时使用的常用习惯用法:
my_report <- function(data, grouping_vars) {
data %>%
group_by_(.dots=grouping_vars) %>%
summarize(x_mean=mean(x), x_median=median(x), ...)
}
Run Code Online (Sandbox Code Playgroud)
这grouping_vars是一个字符串向量.
我喜欢这个成语,因为我可以从其他地方传递字符串向量,例如文件或Shiny应用程序的反应性UI,但它对于交互式工作也不是太糟糕.
但是,在使用dplyr vignette的新编程中,我没有看到使用新的dplyr可以完成这样的事情的示例.我只看到传递字符串不再是正确方法的示例,我必须使用quosures.
我很高兴采用quosures,但是我如何从字符串到dplyr预期的这些情况呢?期望整个R生态系统向dplyr提供数据似乎是不可行的 - 很多时候我们将获得字符串并且它们必须被转换.
这是一个示例,显示您现在应该做什么,以及我的旧习语如何不起作用:
library(dplyr)
grouping_vars <- quo(am)
mtcars %>%
group_by(!!grouping_vars) %>%
summarise(mean_cyl=mean(cyl))
#> # A tibble: 2 × 2
#> am mean_cyl
#> <dbl> <dbl>
#> 1 0 6.947368
#> 2 1 5.076923
grouping_vars <- "am"
mtcars %>%
group_by(!!grouping_vars) %>%
summarise(mean_cyl=mean(cyl))
#> # A tibble: 1 × 2
#> …Run Code Online (Sandbox Code Playgroud) 我正在尝试重命名列,dplyr::rename()R正在返回此错误,我无法在网上找到任何地方.
Error: `new_name` = old_name must be a symbol or a string, not formula
具有2列数据框的可重现示例:
library(dplyr)
df <- data.frame(old_name = seq(1:10), x = seq(1:10))
df %>% dplyr::rename(new_name = old_name)
Run Code Online (Sandbox Code Playgroud)
会话信息:
> sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin17.2.0 (64-bit)
Running under: macOS High Sierra 10.13.1
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] dplyr_0.7.4
loaded via a namespace (and not attached): …Run Code Online (Sandbox Code Playgroud) 我试图使用以下功能,但每次我这样做,我收到以下错误.我尝试安装旧版本的rlang,因为它适用于不同的R Studio,但我无法做到这一点.似乎错误是由0.3.0版本引起的.任何有关如何解决此错误的建议将不胜感激.
details2 <-
details %>%
mutate(rownames=rownames(.)) %>%
filter(isdir==FALSE) %>%
arrange(desc(ctime))
Error in mutate_impl(.data, dots) :
Evaluation error: `as_dictionary()` is defunct as of rlang 0.3.0.
Please use `as_data_pronoun()` instead.
Run Code Online (Sandbox Code Playgroud) aes_string had some convenient behaviours that I made use of when programming with ggplot2. But aes_string has been deprecated (noticeably since ggplot2 version 3.4.0 I believe). I am struggling with how to nicely replace it.
Specifically, I previously created functions that accepted arbitrary string arguments through the ellipsis, and passed these to aes_string via do.call, as shown in the first reprex below.
\nSince noticing the deprecation warning I have tried to avoid aes_string, and found myself effectively …
library(dplyr) #Devel version, soon-to-be-released 0.6.0
library(tidyr)
library(ggplot2)
library(forcats) #for gss_cat data
Run Code Online (Sandbox Code Playgroud)
我正在尝试编写一个函数,它结合了即将发布的dplyrdevel版本的quosures tidyr::gather和ggplot2.到目前为止它似乎可以使用tidyr,但我在绘图方面遇到了麻烦.
以下功能似乎适用于tidyr's gather:
GatherFun<-function(gath){
gath<-enquo(gath)
gss_cat%>%select(relig,marital,race,partyid)%>%
gather(key,value,-!!gath)%>%
count(!!gath,key,value)%>%
mutate(perc=n/sum(n))
}
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何让情节发挥作用.我试着用!!gath用ggplot2,但没有奏效.
GatherFun<-function(gath){
gath<-enquo(gath)
gss_cat%>%select(relig,marital,race,partyid)%>%
gather(key,value,-!!gath)%>%
count(!!gath,key,value)%>%
mutate(perc=n/sum(n))%>%
ggplot(aes(x=value,y=perc,fill=!!gath))+
geom_col()+
facet_wrap(~key, scales = "free") +
geom_text(aes(x = "value", y = "perc",
label = "perc", group = !!gath),
position = position_stack(vjust = .05))
}
Run Code Online (Sandbox Code Playgroud) 我对如何将函数参数传递给dplyr和ggplot代码感到困惑.我正在使用最新版本的dplyr和ggplot2这是我的代码来生成一个条形图(清晰度与平均价格)
diamond.plot<- function (data, group, metric) {
group<- quo(group)
metric<- quo(metric)
data() %>% group_by(!! group) %>%
summarise(price=mean(!! metric)) %>%
ggplot(aes(x=!! group,y=price))+
geom_bar(stat='identity')
}
diamond.plot(diamonds, group='clarity', metric='price')
Run Code Online (Sandbox Code Playgroud)
错误:
Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "packageIQR"
Run Code Online (Sandbox Code Playgroud)
对于最新版本的dplyr,强调不推荐使用强调的verbs_().好像我们应该使用quosures.
我的问题:
上面的代码出了什么问题?(没有下划线dplyr动词请..)
在ggplot中,我知道我们可以使用aes_string(),但在我的例子中,只有一个参数在aes中从函数参数传递.
提前致谢.
我最近注意到这rlang::sym似乎不适用于匿名函数,我不明白为什么.这是一个例子,它非常笨拙和丑陋,但我认为它说明了这一点
require(tidyverse)
data <- tibble(x1 = letters[1:3],
x2 = letters[4:6],
val = 1:3)
get_it <- function(a, b){
data %>%
mutate(y1 = !!rlang::sym(a)) %>%
mutate(y2 = !!rlang::sym(b)) %>%
select(y1, y2, val)
}
get_it("x1", "x2")
Run Code Online (Sandbox Code Playgroud)
这定义了一些玩具数据和一个(可怕的)函数,它基本上根据列名重命名列.现在我可以为a和b的不同组合做同样的事情:
d <- tibble(x = c("x1", "x2"),
y = c("x2", "x1"))
d %>% mutate(tmp = map2(x, y, get_it))
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试使用匿名函数执行完全相同的操作,则它不起作用:
d %>% mutate(tmp = map2(x, y, function(a, b){
data %>%
mutate(y1 = !!rlang::sym(a)) %>%
mutate(y2 = !!rlang::sym(b)) %>%
select(y1, y2, val)
}))
Run Code Online (Sandbox Code Playgroud)
object 'a' not found …
我正在尝试安装“lifecycle”包,但需要 rlangs。
\n输入 install.packages('lifecyle') 时,我收到错误消息,指出我正在导入比所需更新的 rlangs 包(正在加载 'rlang' 0.4.5,但需要 >= 0.4.10)。
\n\n\n\n
\n- 安装源包“lifecycle”...
\n
\n** 包“lifecycle”成功解压并检查 MD5 和
\n** 字节编译并准备包以进行延迟加载
\nloadNamespace(i, c(lib.loc, . libPaths()), versionCheck = vI[[i]]) :
\n正在加载命名空间 'rlang' 0.4.5,但需要 >= 0.4.10
\n错误:程序包 'lifecycle' 延迟加载失败- 删除 R CMD INSTALL 中的“C:/Users/user/R/library/lifecycle”
\n
\ninstall.packages 中的警告:安装包 \xe2\x80\x98lifecycle\xe2\x80\x99\n 具有非零退出状态
我已经卸载了 rlangs 并自行重新安装,但它仍然无法正常工作。
\n不确定这是否有帮助,但我事先收到以下消息:
\n\n\n有可用的二进制版本,但源版本\n稍后:
\n
\nrlang - 二进制:0.4.5 - 源:0.4.10 - Needs_compilation:TRUE
\nlifecycle - 二进制:0.2.0 - 源:1.0.0 - Needs_compilation:FALSE
这个错误没有什么意义,并且与其他具有此类错误的帖子不同。
\nI\'m currently co-developing an R package using devtools. We use the\ntidyverse %>% and associated purrr and dplyr packages within our\nfunctions.
One of our functions is as follows (edited for clarity):
\n#\' Print `cust_modl` object\n#\'\n#\' @param x A `cust_modl` object.\n#\' @param ... Additional arguments passed to `print.cust_modl()` to print the\n#\' object.\n#\'\n#\' @method print cust_modl\n#\' @export\nprint.cust_modl <- function(x, ...) {\n\nreq_var_nms <- x$var %>%\npurrr::compact(.x = .) %>%\nnames(x = .)\n\ncomp_var_ind_filt <- req_var_nms %>%\npurrr::map(.x = ., .f = ~ purrr::pluck(x$var, .x))\n\n}\nRun Code Online (Sandbox Code Playgroud)\n …