下面是我使用 dplyr 按组标准化的代码示例:
mtcars %>% group_by(carb) %>% mutate(norm = (hp - min(hp)) / (max(hp) - min(hp))) %>% ungroup()
我想修改此代码,以便可以使用“across”或“purr”或其他任何函数将标准化同时应用于多个特定列。有人可以帮忙吗?
或者其他什么
好吧,然后是Base R。你可以试试
min_max_norm = \(x) { (x - min(x)) / (max(x) - min(x)) }
iris[, sapply(iris, is.numeric)] = lapply(iris[, sapply(iris, is.numeric)], min_max_norm)
这给出了
> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 0.22222222 0.6250000 0.06779661 0.04166667 setosa
2 0.16666667 0.4166667 0.06779661 0.04166667 setosa
3 0.11111111 0.5000000 0.05084746 0.04166667 setosa
4 0.08333333 0.4583333 0.08474576 0.04166667 setosa
5 0.19444444 0.6666667 0.06779661 0.04166667 setosa
6 0.30555556 0.7916667 0.11864407 0.12500000 setosa