基于 R 数据帧中其他列中的值缩放列的有效方法 [英] Efficient way of scaling column based on value in other column in R dataframe
问题描述
我想根据另一列中的值缩放 dataframe
列中的值.例如,这里有一个简单的例子
I want to scale values in the column of a dataframe
based on values in another colum. For example, here is a simple example
d<-data.frame(x=runif(5,0,10),y=sample(c(1,2),size=5,replace=TRUE))
给出输出:
x y
1 1.0895865 2
2 0.8261554 2
3 5.3503761 2
4 3.3940759 1
5 6.2786637 1
我想根据 y 值缩放 x 值,所以我想要的是:
I want to scale the x values based on the y values, so what I want is to have:
(x|y=1 - average(x's | y=1))/std.dev(x's|y=1)
然后用缩放后的值替换 d 中的 x 值,对于 x
值与 y=2
类似.
then replace the x values in d with the scaled values, similarly for the x
values with y=2
.
到目前为止我所做的有点笨拙:
What I have done so far is a bit clunky:
d1<-subset(d,y==1)
d2<-subset(d,y==2)
d1$x<-(d1$x-mean(d1$x))/sd(d1$x)
d2$x<-(d2$x-mean(d2$x))/sd(d2$x)
然后将所有结果绑定到一个大数据框中,但这有点乏味,因为我的实际数据有 50 个不同的 y 值,我想为多个(不同)列执行此操作.
and then binding all the results in one big data frame, but this is a bit tedious since my actual data has 50 different values for y and I'd like to do this for multiple (different) columns.
推荐答案
您可以使用 dplyr
中的 group_by
和 mutate
轻松完成此操作包:
You can easily do this using group_by
and mutate
from the dplyr
package:
require(dplyr)
d %>%
group_by(y) %>%
mutate(x = (x - mean(x)) / sd(x))
这篇关于基于 R 数据帧中其他列中的值缩放列的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!