silent_hunter
silent_hunter

Reputation: 2508

Use paste command with dplyr

I am trying to use paste command in order to paste some part of string into command group_by from dyplyr. This how is look like code normally without paste.

library(dplyr)
   DATA1<-DATA%>%
dplyr::group_by(id_n,gross_income)%>%
dplyr::summarize(gross_i=sum(gross_i)

So now I want to use paste command, and I try with this line of code.

  query_type1<-"id_n,gross_income"

Next step is to implement this line of code in code above.

   DATA1<-DATA%>%
dplyr::group_by(query_type1)%>%
dplyr::summarize(gross_i=sum(gross_i)

But unfortunately this don't give me good result. So can anybody help me how to fix this line of code?

Upvotes: 0

Views: 313

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388982

As others have already suggested have column names as vector instead of one comma-separated string.

query_type1<- c("id_n","gross_income")

You can then use across in group_by :

library(dplyr)

DATA%>%
  group_by(across(query_type1)) %>%
  summarize(gross_i=sum(gross_i)

Upvotes: 2

latlio
latlio

Reputation: 1587

Another solution is to use the rlang package within the tidyverse. exprs "defuses" an expression, which means it can take values (that don't need to be in quotes) and returns the R expression describing how to make the value. !!!, called "unquote-splice", takes a list of arguments and inserts them in the place of !!!

library(tidyverse)

gvars <- exprs(gear, carb)
mtcars %>% 
  group_by(!!!gvars)

Upvotes: 3

Yuriy Saraykin
Yuriy Saraykin

Reputation: 8880

try it like this

library(tidyverse)
gr <- syms(c("vs", "am"))
mtcars %>% 
  group_by(!!!gr) %>% 
  summarise(sum_mpg = sum(mpg))
#> `summarise()` regrouping output by 'vs' (override with `.groups` argument)
#> # A tibble: 4 x 3
#> # Groups:   vs [2]
#>      vs    am sum_mpg
#>   <dbl> <dbl>   <dbl>
#> 1     0     0    181.
#> 2     0     1    118.
#> 3     1     0    145.
#> 4     1     1    199.

Created on 2021-01-12 by the reprex package (v0.3.0)

Upvotes: 3

Related Questions