Sha*_*ang 3 r max dataframe data.table
我有以下R data.table:
library(data.table)
iris = as.data.table(iris)
> iris
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
7 4.6 3.4 1.4 0.3 setosa
8 5.0 3.4 1.5 0.2 setosa
...
Run Code Online (Sandbox Code Playgroud)
比方说,我希望通过每一行找到在行的最大值,仅data.table列的子集:Sepal.Length,Sepal.Width,Petal.Length,Petal.Width
我将使用以下代码:
iris[, maximum_element :=max(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width), by=1:nrow(iris)]
Run Code Online (Sandbox Code Playgroud)
哪个输出
Sepal.Length Sepal.Width Petal.Length Petal.Width Species maximum_element
1: 5.1 3.5 1.4 0.2 setosa 5.1
2: 4.9 3.0 1.4 0.2 setosa 4.9
3: 4.7 3.2 1.3 0.2 setosa 4.7
4: 4.6 3.1 1.5 0.2 setosa 4.6
5: 5.0 3.6 1.4 0.2 setosa 5.0
Run Code Online (Sandbox Code Playgroud)
对于我的问题,我实际上对该值不感兴趣,但是该值来自哪一列,即我想要以下输出:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species maximum_column
1: 5.1 3.5 1.4 0.2 setosa Sepal.Length
2: 4.9 3.0 1.4 0.2 setosa Sepal.Length
3: 4.7 3.2 1.3 0.2 setosa Sepal.Length
4: 4.6 3.1 1.5 0.2 setosa Sepal.Length
5: 5.0 3.6 1.4 0.2 setosa Sepal.Length
Run Code Online (Sandbox Code Playgroud)
(在这种情况下,每个最大值都来自Sepal.Length)。
如何“检索”具有最大值的列名?
这是一个选项 pmax
iris[, maximum_element := do.call(pmax, .SD), .SDcols = 1:4]
Run Code Online (Sandbox Code Playgroud)
并查找列名,max.col在.SD将.SDcols用作数字列(即列1至4)后使用
iris[,maximum_column := names(.SD)[max.col(.SD)], .SDcols = 1:4]
head(iris, 4)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species maximum_column
#1: 5.1 3.5 1.4 0.2 setosa Sepal.Length
#2: 4.9 3.0 1.4 0.2 setosa Sepal.Length
#3: 4.7 3.2 1.3 0.2 setosa Sepal.Length
#4: 4.6 3.1 1.5 0.2 setosa Sepal.Length
Run Code Online (Sandbox Code Playgroud)