my function is going to take data and column name from user.
column name must be passed only like : column
or my column
(ie, no "" s only backticks if column name is multi words)
at part of my function I need to check for missing values in that column and replace them with "missed".
myfun <- function(data, column){
library(tidyverse)
data <- as.tibble(data)
data %>%
mutate(across(.cols = {{column}}, .fns = as.character)) %>%
replace_na(list({{columns}} = "missed"))
}
new_df <- airquality %>%
myfun(Ozone)
I used {{}}
before and I had no issues passing column names like airquality example above. Now at part of my actual function, I need to replace na s . the format above does not work with replace_na() .
any idea how to fix this?
CodePudding user response:
I think you need to use replace_na()
within mutate()
. If you use the same strategy as for converting your columns to character, this seems to solve the problem:
myfun <- function(data, column){
library(tidyverse)
data <- as_tibble(data)
data %>%
mutate(across(.cols = {{column}}, .fns = ~ replace_na(as.character(.x), "missed")))
}
new_df <- airquality %>%
myfun(Ozone)
The output:
> head(new_df)
# A tibble: 6 × 6
Ozone Solar.R Wind Temp Month Day
<chr> <int> <dbl> <int> <int> <int>
1 41 190 7.4 67 5 1
2 36 118 8 72 5 2
3 12 149 12.6 74 5 3
4 18 313 11.5 62 5 4
5 missed NA 14.3 56 5 5
6 28 NA 14.9 66 5 6