Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr::mutate all numeric variables except one?

Tags:

r

dplyr

across

Is there a way to mutate all numeric variables except one (in this case age) or two?

data

data = data.frame(
    Year = c(1,2,5,7,2,6,2,6),
    days = c(5,3,6,3,7,2,5,7),
    age = c(1,3,5,23,2,4,5,2),
    names = c("A063", "A013", "A063", "A083", "A019", "A012", "A013", "A113"))

Something like this: I want to scale all numeric terms except age

data = mutate(across(where(is.numeric & !age), scale))
like image 775
Ian.T Avatar asked Jun 05 '26 17:06

Ian.T


2 Answers

One option could be:

data %>%
 mutate(across(c(where(is.numeric), -age), scale))

        Year       days age names
1 -1.2199771  0.1309842   1  A063
2 -0.7956372 -0.9168895   3  A013
3  0.4773823  0.6549210   5  A063
4  1.3260620 -0.9168895  23  A083
5 -0.7956372  1.1788579   2  A019
6  0.9017222 -1.4408263   4  A012
7 -0.7956372  0.1309842   5  A013
8  0.9017222  1.1788579   2  A113
like image 103
tmfmnk Avatar answered Jun 07 '26 07:06

tmfmnk


We could use setdiff on the selected names where the columns are numeric and apply the scale

library(dplyr)
out <- data %>%
   mutate(across(setdiff(names(select(., where(is.numeric))), 'age'), scale))
out
#        Year       days age names
#1 -1.2199771  0.1309842   1  A063
#2 -0.7956372 -0.9168895   3  A013
#3  0.4773823  0.6549210   5  A063
#4  1.3260620 -0.9168895  23  A083
#5 -0.7956372  1.1788579   2  A019
#6  0.9017222 -1.4408263   4  A012
#7 -0.7956372  0.1309842   5  A013
#8  0.9017222  1.1788579   2  A113

Or another option with imap

library(purrr)
data %>%
   imap_dfc(~ if(is.numeric(.x) & .y != 'age') scale(.x) else .x)

Or using base R

i1 <- sapply(data, is.numeric) & names(data) != "age"
data[i1] <- lapply(data[i1], scale)
like image 40
akrun Avatar answered Jun 07 '26 06:06

akrun