创建数据
df <- data.frame(x=c(1,2,3,4),y=c(7,4,6,10),z=c(5,6,9,12))
rownames(df) <- LETTERS[1:nrow(df)]
df
x y z
A 1 7 5
B 2 4 6
C 3 6 9
D 4 10 12
试运行
-
scale
函数直接运行
scale_df <- as.data.frame(scale(df))
scale_df
x y z
A -1.1618950 0.1 -0.9486833
B -0.3872983 -1.1 -0.6324555
C 0.3872983 -0.3 0.3162278
D 1.1618950 1.3 1.2649111
- 自定义
scale
函数直接运行,此处以行为单位批量运行
scale_df2 =apply(df,1,scale)
scale_df2
A B C D
[1,] -1.0910895 -1 -1 -1.1208971
[2,] 0.8728716 0 0 0.3202563
[3,] 0.2182179 1 1 0.8006408
- 单次运行数组(数据框中的行)
scale(c(1,7,5))
[,1]
[1,] -1.0910895
[2,] 0.8728716
[3,] 0.2182179
attr(,"scaled:center")
[1] 4.333333
attr(,"scaled:scale")
[1] 3.05505
- 单次运行数组(数据框中的列)
scale(c(1,2,3,4))
[,1]
[1,] -1.1618950
[2,] -0.3872983
[3,] 0.3872983
[4,] 1.1618950
attr(,"scaled:center")
[1] 2.5
attr(,"scaled:scale")
[1] 1.290994
结论
综上,假如以行为单位进行统一的归一化处理,正确的代码如下
scale_df2 = t(apply(df,1,scale))
网友评论