我想在dataframe(df)中添加一个变量(列),在每行中包含第2到第26列的该行的最大值.
对于第一行,代码将是:
df$max[1] <- max(df[1,2:26])
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种方法来概括第1行到第865行.如果我给:
df$max[1:865] <- max(df[1:865, 2:26])
Run Code Online (Sandbox Code Playgroud)
我得到变量所有行的总体最大值df$max.
Sha*_*ane 41
你可以用apply.例如:
df[, "max"] <- apply(df[, 2:26], 1, max)
Run Code Online (Sandbox Code Playgroud)
这是一个基本的例子:
> df <- data.frame(a=1:50, b=rnorm(50), c=rpois(50, 10))
> df$max <- apply(df, 1, max)
> head(df, 2)
a b c max
1 1 1.3527115 9 9
2 2 -0.6469987 20 20
> tail(df, 2)
a b c max
49 49 -1.4796887 10 49
50 50 0.1600679 13 50
Run Code Online (Sandbox Code Playgroud)
这里有两个额外的方法。在基数 R 中,第一个是将矩阵提取[与相结合max.col,它返回一个向量,索引每行中最大值的列位置。
df$max <- df[2:26][cbind(seq_len(nrow(df)), max.col(df[2:26]))]
Run Code Online (Sandbox Code Playgroud)
cbind构造一个矩阵,索引每一行的最大值的位置,并[使用它来提取这个值。
二是rowMaxs在matrixStats包中使用。这看起来像
library(matrixStats)
rowMaxs(as.matrix(df[2:26])))
Run Code Online (Sandbox Code Playgroud)
让我们做一些基准测试。
# data.frame with 1000 observations and 26 variables
set.seed(1234)
df <- data.frame(id=paste0(letters[-1], 1:40), matrix(rnorm(25000L, 5L, 10L), 1000L))
Run Code Online (Sandbox Code Playgroud)
还将包中的rowMaxs功能添加matrixStats到组合中。
library(matrixStats)
library(microbenchmark)
microbenchmark(apply=apply(df[, 2:26], 1, max),
pmax=do.call(pmax, df[2:26]),
max.colSub=df[2:26][cbind(seq_len(nrow(df)), max.col(df[2:26]))],
rowMaxs=rowMaxs(as.matrix(df[2:26])))
Unit: microseconds
expr min lq mean median uq max neval cld
apply 1610.540 1786.5905 2193.5334 1863.5680 1990.4380 6915.999 100 c
pmax 354.382 364.6455 380.1720 373.3405 385.4580 567.923 100 a
max.colSub 604.416 651.7430 822.6015 664.7155 681.2510 3086.512 100 b
rowMaxs 243.762 264.0040 320.2350 277.9750 290.5190 2328.712 100 a
Run Code Online (Sandbox Code Playgroud)
所以,rowMaxs是明显的赢家,然后是pmax,然后是max.col,带有矩阵提取,并apply在包的尾端。
使用具有 10000 行和 26 列的 data.frame,我们得到了类似的故事:
set.seed(1234)
df <- data.frame(id=paste0(letters[-1], 1:400), matrix(rnorm(250000L, 5L, 10L), 10000L))
Run Code Online (Sandbox Code Playgroud)
上面的代码返回
Unit: milliseconds
expr min lq mean median uq max neval cld
apply 15.193361 18.299830 21.737516 20.337880 21.774793 99.44836 100 c
pmax 3.060853 3.101481 3.156630 3.137545 3.191430 3.54182 100 a
max.colSub 3.338828 3.642603 7.051700 3.992708 6.336531 84.43119 100 b
rowMaxs 1.244184 1.322302 2.675281 1.508474 1.638053 79.28054 100 a
Run Code Online (Sandbox Code Playgroud)