问题描述
是否有一种方法可以对所有数字变量进行突变(除了一个(在这种情况下为年龄)或两个)?
数据
data = data.frame(
Year = c(1,2,5,7,6,6),days = c(5,3,7),age = c(1,23,4,2),names = c("A063","A013","A063","A083","A019","A012","A113"))
这样的事情:我想缩放除年龄之外的所有数字术语
data = mutate(across(where(is.numeric & !age),scale))
解决方法
一个选项可能是:
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
,
我们可以在setdiff
版select
names
上使用where
,将列设为numeric
并应用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
或带有imap
library(purrr)
data %>%
imap_dfc(~ if(is.numeric(.x) & .y != 'age') scale(.x) else .x)
或使用base R
i1 <- sapply(data,is.numeric) & names(data) != "age"
data[i1] <- lapply(data[i1],scale)