我有下列R- 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
...
比方说,我希望通过每一行找到在行的最大值,仅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)]
,输出
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
对于我的问题,我其实不感兴趣的值,但列中的值是从哪里来的,也就是我想下面的输出:
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
(在这种情况下,最大。值各自来自Sepal.Length
)。
如何“检索”具有最大值的列名?
[this]的可能重复(https://stackoverflow.com/questions/28909684/calculate-row-wise-maximum/28910623#28910623)或[this](https://stackoverflow.com/ques tions/33768847/how-to-create-a-new-column-based-other-columns-in-a-data-table/33769378) –