dplyr::mutate如何对除一个变量以外的所有数字变量进行操作?

8

有没有一种方法可以变异除年龄之外或除两个变量之外的所有数值变量?

数据

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"))

类似这样:我想对除年龄以外的所有数字项进行比例缩放

data = mutate(across(where(is.numeric & !age), scale))
2个回答

23

一个选择可能是:

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

2
请注意,在 c() 中,-age 必须放在 where(is.numeric) 之后。 - Giovanni Colitti

4

我们可以使用setdiff在选定的names上,其列为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)

或者使用 基本R语言

i1 <- sapply(data, is.numeric) & names(data) != "age"
data[i1] <- lapply(data[i1], scale)

@Ian.T 抱歉,没有检查更新。现在已经更新了帖子。 - akrun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接