Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use dynamic column name in quantile function in R?

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone help me?

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading