【发布时间】:2018-10-02 21:26:50
【问题描述】:
我的数据框设置如下:
Black White Red Blue
0.8 0.1 0.07 0.03
0.3 0.6 0 0.1
0.1 0.6 0.25 0.05
我希望我的数据框看起来像这样:
Black White Red Blue Color1 Color2 Color3 Color4
0.8 0.1 0.07 0.03 0.8 0.1 0.07 0.03
0.3 0.6 0 0.1 0.6 0.3 0.1 0
0.1 0.6 0.25 0.05 0.6 0.25 0.1 0.05
其中Color1代表每行最大值,Color2代表第二大值,Color3代表第三大值,Color4代表每行最小值。
到目前为止,我已经使用这个函数来获得我想要的,也就是上面的结果:
maxn <- function(n) function(x) order(x, decreasing = TRUE)[n]
df$Color1 <- apply(df, 1, max)
df$Color2 <- apply(df, 1, function(x)x[maxn(3)(x)])
df$Color3 <- apply(df, 1, function(x)x[maxn(4)(x)])
df$Color4 <- apply(df, 1, function(x)x[maxn(5)(x)])
有没有更简洁的方式来安排我的数据集?
另外,有点跑题了:我不确定是不是因为这是一个 CSV 文件,每当我使用该函数时都会使用它
df$Color2 <- apply(df, 1, function(x)x[maxn(2)(x)])
它将返回与函数相同的结果
apply(df, 1, max)
与
apply(df, 1, function(x)x[maxn(1)(x)])
【问题讨论】: