0

I have trouble with dynamic variable that I want to use in quantile function.

I tried to use paste0 for column name, that I want to use:

m = "01"
quantile_s = data %>%
  group_by(col1, col2) %>%
  summarise(quant1 = quantile(data[[paste0("col3_", m)]], prob=0.75, type=2, na.rm = TRUE)

But in the result, instead of the right answer, it returns the same value in every observation...

Can someone help me?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
rstatlt
  • 63
  • 4

1 Answers1

0

How about this, it wraps the paste statement in !!sym()

data(mtcars)
library(rlang)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

mtcars %>% group_by(cyl) %>% 
  summarise(quant1 = quantile(!!sym(paste0("h", "p")), prob=.75, type=2, na.rm=TRUE))
#> # A tibble: 3 × 2
#>     cyl quant1
#>   <dbl>  <dbl>
#> 1     4     97
#> 2     6    123
#> 3     8    245

Created on 2022-02-17 by the reprex package (v2.0.1)

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25