0

I am trying to change the values of a tibble column in a place using a function. However, I am not managing it. Perhaps somebody could help. I made a simple reproducible example:

noga2 <- tibble(a = c(1,12), b=c(12,3))
iot_test <- function(data, selcol) {
   data <- data %>%  mutate(UQ(selcol):= if_else(str_length((selcol)) == 2,"TA","0"))
   return(data)
}
iot_test(noga2, "a")

This is the result:

  a         b
 <chr> <dbl>
1 0        12
2 0         3

But the idea is to have only the second value in the column a to be changed.

Thanks Renger

arnyeinstein
  • 669
  • 1
  • 5
  • 14

1 Answers1

1

You can use ensym on selcol if you are passing it as a character. You then need a double bang to unquote selcol where it is being used.

noga2 <- tibble(a = c(1, 12), b = c(12, 3))

iot_test <- function(data, selcol) {   
   selcol <- ensym(selcol)
   mutate(data, !!selcol := if_else(str_length(!!selcol) == 2, "TA", "0"))
}

iot_test(noga2, "a")
#> # A tibble: 2 x 2
#>   a         b
#>   <chr> <dbl>
#> 1 0        12
#> 2 TA        3
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87