0

Been trying to do something very simple, but I'm still having troubles with tidyeval. I have a numeric column from a dataframe and want to turn it into a string, let's say:

id code
1   10
2   14

And I want to turn code into a string in this case, using a function that accepts a column name as argument. I tried many variations and have not been able to do so:

pre_process <- function(df, num_col) {
  

  df <- df %>%
    mutate ({{num_col}} := toString({{num_col}}))

Tried using = instead of :=, using !!!, !! and a couple other but nothing seems to work, if there's no errors what I get is a dataframe like this:

id   code
1   "code"
2   "code"

What am I missing? Thanks

Juan C
  • 5,846
  • 2
  • 17
  • 51
  • 3
    How are you calling it? `pre_process(dat, "code")` produces the errant output, but `pre_process(dat, code)` works: for all rows, `code` is `"10, 14"`, I'm hoping that is what you intended. (If all you wanted was for each value to be converted to strings, as in `"10"` and `"14"`, then you should use `as.character` instead of `toString`. Perhaps the latter is poorly named ...) – r2evans Aug 27 '21 at 17:59
  • 1
    Thanks a lot @r2evans for both inputs, you guessed right both times. Still getting used to going from python to R – Juan C Aug 27 '21 at 18:03
  • Non-standard evaluation (NSE) in R can be a very tricky thing to get right. I'm comfortable enough with it but still have to play with things a bit to get it right. However ... I don't know that is adds any real value in this case: `pre_process <- function(df, num_col) { df[[num_col]] <- as.character(df[[num_col]]); df; }` is (to me) just as clear, and it doesn't have any NSE hoops to jump through. – r2evans Aug 27 '21 at 18:05
  • Or in this case, rather than bothering with `:=`, you can use the `across()` function to apply a transformation to a column (or columns): `pre_process <- function(df, num_col) {df %>% mutate (across({{num_col}), as.character))}`. Also note that you can't reassign the global `df` from inside the function. Make sure to return the updated value and reassign `df <- pre_process(df, code)` – MrFlick Aug 27 '21 at 18:08
  • In reality this is only one part of a bigger pipeline, so I would think using NSE might be better still. But I'll consider if using standard notation might be better in the end anyways. – Juan C Aug 27 '21 at 18:12
  • @MrFlick, so there's curly and curly-curly to know about? NSE and all the exceptions needed to make it work is gonna make me bald – Juan C Aug 27 '21 at 18:12
  • 1
    Have you read the [programming with dplyr](https://dplyr.tidyverse.org/articles/programming.html) guide? All the important stuff is introduced there (including `{{}}` which is called "embrace") – MrFlick Aug 27 '21 at 18:13
  • @MrFlick blessed link! Had found other articles on tidyeval, but this seems more comprehensive and ordered. Thanks a lot – Juan C Aug 27 '21 at 18:37

0 Answers0