在`dplyr`动词中使用未加引号的字符串:`select`和`arrange`的工作方式不同 [英] Using unquoted strings in with `dplyr` verbs: `select` and `arrange` working differently

查看:62
本文介绍了在`dplyr`动词中使用未加引号的字符串:`select`和`arrange`的工作方式不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试取消引用在 dplyr :: arrange 中使用的字符串.它似乎不起作用.但是,它在 dplyr :: select 中似乎可以正常工作.我在这里错过了什么还是做错了什么?

I am trying to unquote a string for use in dplyr::arrange. It does not appear to work. However, it appears to work correctly in dplyr::select. Am I missing something or doing something wrong here?


library(tidyverse)

df <- tibble(x = c(1, 2, 3),
             y = c(8, 6, 3))

v <- 'y'

# `select` works with `!!v` 

df %>% select(y)
#> # A tibble: 3 x 1
#>       y
#>   <dbl>
#> 1     8
#> 2     6
#> 3     3

df %>% select(!!v)
#> # A tibble: 3 x 1
#>       y
#>   <dbl>
#> 1     8
#> 2     6
#> 3     3

# `arrange` not work with `!!v`

df %>% arrange(y)
#> # A tibble: 3 x 2
#>       x     y
#>   <dbl> <dbl>
#> 1     3     3
#> 2     2     6
#> 3     1     8

df %>% arrange(!!v)
#> # A tibble: 3 x 2
#>       x     y
#>   <dbl> <dbl>
#> 1     1     8
#> 2     2     6
#> 3     3     3

推荐答案

您需要先将字符串转换为变量(使用 sym()),然后在 arrange().

You need to convert your string to variable first (using sym()) then unquote it inside arrange().

df %>% arrange(!!sym(v))

#> # A tibble: 3 x 2
#>       x     y
#>   <dbl> <dbl>
#> 1     3     3
#> 2     2     6
#> 3     1     8

select()可以直接接受字符串输入,但不建议

select() can directly take string input but it's not recommended

df %>% select(v)

#> Note: Using an external vector in selections is ambiguous.
#> i Use `all_of(v)` instead of `v` to silence this message.
#> i See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.
#> This message is displayed once per session.
#> # A tibble: 3 x 1
#>       y
#>   <dbl>
#> 1     8
#> 2     6
#> 3     3

reprex软件包(v0.3.0)创建于2020-11-21 sup>

Created on 2020-11-21 by the reprex package (v0.3.0)

这篇关于在`dplyr`动词中使用未加引号的字符串:`select`和`arrange`的工作方式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆