'Get a character without quotes while still being a character

For a dataframe as follows:

Concentration  Value
Low            0.21
Medium         0.85
Low            0.10
Low            0.36
High           2.21
Medium         0.50
High           1.85

I want to execute the following function to tranpose the factors of a variable into the columns of the new dataframe.

This works just fine:

df <- df %>% 
  group_by(var1) %>% 
  mutate(id = row_number()) %>% 
  pivot_wider(names_from = var1, values_from = var2)

However, (as I'm working in Rshiny), we do not know the name of the variables before-hand, as they are established by the user's of the app selection. And we would have one variable called input$num_var_1, which corresponds to "Concentration".

As you can see, "Concentration" will make the previous function fail it's purpose as the variable needs to be named without quotation marks.

This can be achieved in many different ways (noquote(input$num_var_1), cat(input$num_var_1, "\n")

However, all this functions change the type of object, from character, to somehthing else (noquote, NULL, etc), and group_by() needs to be used over either a character or a number.

How can I call for the variable without quotes and without chaging the variable type?

r


Solution 1:[1]

This is not about quotation marks. The quotation marks are simply what R puts around character vectors when it prints them to the screen. The problem is that you want the input to be interpreted as a symbol rather than a character. To convert characters to symbols we can use ensym from rlang:

library(tidyverse)

myfunc <- function(df, var1, var2)
{
  var1 <- ensym(var1)
  var2 <- ensym(var2)
  
  df %>% 
    group_by(!!var1) %>% 
    mutate(id = row_number()) %>% 
    pivot_wider(names_from = !!var1, values_from = !!var2)
}

This allows:

myfunc(df, "Concentration", "Value")
#> # A tibble: 3 x 4
#>      id   Low Medium  High
#>   <int> <dbl>  <dbl> <dbl>
#> 1     1  0.21   0.85  2.21
#> 2     2  0.1    0.5   1.85
#> 3     3  0.36  NA    NA

Created on 2022-04-11 by the reprex package (v2.0.1)


Data taken from question in reproducible format

df <- structure(list(Concentration = c("Low", "Medium", "Low", "Low", 
"High", "Medium", "High"), Value = c(0.21, 0.85, 0.1, 0.36, 2.21, 
0.5, 1.85)), class = "data.frame", row.names = c(NA, -7L))

df
#>   Concentration Value
#> 1           Low  0.21
#> 2        Medium  0.85
#> 3           Low  0.10
#> 4           Low  0.36
#> 5          High  2.21
#> 6        Medium  0.50
#> 7          High  1.85

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allan Cameron