replace_vars
could replace any value(s) or values
that match specific patterns to another specific value in a data.table.
replace_vars(.data, ..., from = is.na, to)
A data.table.
iris %>% as.data.table() %>%
mutate(Species = as.character(Species))-> new_iris
new_iris %>%
replace_vars(Species, from = "setosa",to = "SS")
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <num> <num> <num> <num> <char>
#> 1: 5.1 3.5 1.4 0.2 SS
#> 2: 4.9 3.0 1.4 0.2 SS
#> 3: 4.7 3.2 1.3 0.2 SS
#> 4: 4.6 3.1 1.5 0.2 SS
#> 5: 5.0 3.6 1.4 0.2 SS
#> ---
#> 146: 6.7 3.0 5.2 2.3 virginica
#> 147: 6.3 2.5 5.0 1.9 virginica
#> 148: 6.5 3.0 5.2 2.0 virginica
#> 149: 6.2 3.4 5.4 2.3 virginica
#> 150: 5.9 3.0 5.1 1.8 virginica
new_iris %>%
replace_vars(Species,from = c("setosa","virginica"),to = "sv")
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <num> <num> <num> <num> <char>
#> 1: 5.1 3.5 1.4 0.2 SS
#> 2: 4.9 3.0 1.4 0.2 SS
#> 3: 4.7 3.2 1.3 0.2 SS
#> 4: 4.6 3.1 1.5 0.2 SS
#> 5: 5.0 3.6 1.4 0.2 SS
#> ---
#> 146: 6.7 3.0 5.2 2.3 sv
#> 147: 6.3 2.5 5.0 1.9 sv
#> 148: 6.5 3.0 5.2 2.0 sv
#> 149: 6.2 3.4 5.4 2.3 sv
#> 150: 5.9 3.0 5.1 1.8 sv
new_iris %>%
replace_vars(Petal.Width, from = .2,to = 2)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <num> <num> <num> <num> <char>
#> 1: 5.1 3.5 1.4 2.0 SS
#> 2: 4.9 3.0 1.4 2.0 SS
#> 3: 4.7 3.2 1.3 2.0 SS
#> 4: 4.6 3.1 1.5 2.0 SS
#> 5: 5.0 3.6 1.4 2.0 SS
#> ---
#> 146: 6.7 3.0 5.2 2.3 sv
#> 147: 6.3 2.5 5.0 1.9 sv
#> 148: 6.5 3.0 5.2 2.0 sv
#> 149: 6.2 3.4 5.4 2.3 sv
#> 150: 5.9 3.0 5.1 1.8 sv
new_iris %>%
replace_vars(from = .2,to = NA)
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <num> <num> <num> <num> <char>
#> 1: 5.1 3.5 1.4 2.0 SS
#> 2: 4.9 3.0 1.4 2.0 SS
#> 3: 4.7 3.2 1.3 2.0 SS
#> 4: 4.6 3.1 1.5 2.0 SS
#> 5: 5.0 3.6 1.4 2.0 SS
#> ---
#> 146: 6.7 3.0 5.2 2.3 sv
#> 147: 6.3 2.5 5.0 1.9 sv
#> 148: 6.5 3.0 5.2 2.0 sv
#> 149: 6.2 3.4 5.4 2.3 sv
#> 150: 5.9 3.0 5.1 1.8 sv
new_iris %>%
replace_vars(is.numeric, from = function(x) x > 3, to = 9999 )
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> <num> <num> <num> <num> <char>
#> 1: 9999 9999.0 1.4 2.0 SS
#> 2: 9999 3.0 1.4 2.0 SS
#> 3: 9999 9999.0 1.3 2.0 SS
#> 4: 9999 9999.0 1.5 2.0 SS
#> 5: 9999 9999.0 1.4 2.0 SS
#> ---
#> 146: 9999 3.0 9999.0 2.3 sv
#> 147: 9999 2.5 9999.0 1.9 sv
#> 148: 9999 3.0 9999.0 2.0 sv
#> 149: 9999 9999.0 9999.0 2.3 sv
#> 150: 9999 3.0 9999.0 1.8 sv