I'm writing an R script and I need to allow user to specify the name of variable that will be proccessed by hand, i.e.
var <- 'user_name'
Generally then I refer to that using rlang::sym and quoting/unquoting mechanism. However, I need to use tidyr::replace_na and none of my ideas worked here as the name of the variable has to be specified inside list.
How can I refer to my var in such a case? I was thinking about something like below:
data <- data %>% replace_na(list(sym(var) = 0))
But it didn't work...
We can also put replace_na inside mutate and unquote:
library(dplyr)
library(tidyr)
var <- 'user_name'
data %>%
mutate(!!var := replace_na(!!sym(var), 0))
Result:
user_name
1 0
2 1
3 2
4 3
5 4
6 5
Data:
data <- data.frame(user_name = c(NA, 1:5))
Without using any external packages other than dplyr/tidyr, we can change this with setNames
library(dplyr)
library(tidyr)
data %>%
replace_na(as.list(setNames(0, var)))
# user_name
#1 0
#2 3
#3 4
data <- data.frame(user_name = c(NA, 3, 4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With