本文介绍了使用tidyeval编程:tidyr :: unite(col = !! col)之后的mutate函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想用tidyr的 unite()创建一个函数,但这似乎不起作用.

So I want to make a function with unite() from tidyr, but it does not seem to work..

library(dplyr, warn.conflicts = FALSE)
library(tidyr, warn.conflicts = FALSE)
library(stringr, warn.conflicts = FALSE)


mtcars %>% 
  as_tibble() %>% 
  select(mpg , cyl) %>% 
  mutate_all(as.character) %>% 
  unite(col = hello, sep = "/") %>% 
  mutate(hello = str_replace(hello, "/", ""))
#> # A tibble: 32 x 1
#>    hello
#>    <chr>
#>  1 216  
#>  2 216  
#>  3 22.84
#>  4 21.46
#>  5 18.78
#>  6 18.16
#>  7 14.38
#>  8 24.44
#>  9 22.84
#> 10 19.26
#> # ... with 22 more rows



# Now I want to make it a function where I choose the colomn name i unite()
unite_fun <- function(df, var1 = mpg, var2 = cyl, col_name = hello){
  var1 <- enquo(var1)
  var2 <- enquo(var2)
  col_name <- enquo(col_name)

  mtcars %>% 
    as_tibble() %>% 
    select(!!var1 , !!var2) %>% 
    mutate_all(as.character) %>% 
    unite(col = !!col_name, sep = "/") %>% 
    mutate(col_name = str_replace(col_name, "/", "")) # how do I refer to col_name here in mutate


}

如何使用我在mutate中统一选择的列名称?

How do I use the column name I have chosen in unite in mutate?

推荐答案

我不确定这是否是最好的方法,但是可以选择使用 quo_name 中引用它>变异

I am not sure if this is the best way to do this but an option is to use quo_name to refer it in mutate

library(tidyverse)
library(rlang)

unite_fun <- function(df, var1 = mpg, var2 = cyl, col_name = hello){
   var1 <- enquo(var1)
   var2 <- enquo(var2)
   col_name <- enquo(col_name)
   col1_name <- quo_name(col_name)

  mtcars %>% 
     as_tibble() %>% 
     select(!!var1 , !!var2) %>% 
     mutate_all(as.character) %>% 
     unite(col = !!col_name, sep = "/")  %>%
     mutate(!!col1_name := str_replace(!!col_name, "/", ""))
}

unite_fun(mtcars, mpg, cyl)
# A tibble: 32 x 1
#   hello
#   <chr>
# 1 216  
# 2 216  
# 3 22.84
# 4 21.46
# 5 18.78
# 6 18.16
# 7 14.38
# 8 24.44
# 9 22.84
#10 19.26
# … with 22 more rows

这篇关于使用tidyeval编程:tidyr :: unite(col = !! col)之后的mutate函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 07:47