计算行向最大值 [英] Calculate row-wise maximum

查看:119
本文介绍了计算行向最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个新列,等于该行所有列的最大值。

I would like to create a new column, which equals to the maximum value of all columns of that row.

这里是一个示例:

library(data.table)
data <- data.table(head(iris))
data[ , Species := NULL]
data

   Sepal.Length Sepal.Width Petal.Length Petal.Width
1:          5.1         3.5          1.4         0.2
2:          4.9         3.0          1.4         0.2
3:          4.7         3.2          1.3         0.2
4:          4.6         3.1          1.5         0.2
5:          5.0         3.6          1.4         0.2
6:          5.4         3.9          1.7         0.4

我不能真正使用 max 函数,因为它会找到最大所有列的值,例如 data [,max_value:= max(Sepal.Length,Sepal.Width,Petal.Length,Petal.Width)] 。我想要的是这样的:

I can't really use the max function here, because it is going to find the maximum value of all columns, e.g., data[, max_value := max(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width)]. What I want is something like this:

   Sepal.Length Sepal.Width Petal.Length Petal.Width max_value
1:          5.1         3.5          1.4         0.2       5.1
2:          4.9         3.0          1.4         0.2       4.9
3:          4.7         3.2          1.3         0.2       4.7
4:          4.6         3.1          1.5         0.2       4.6
5:          5.0         3.6          1.4         0.2       5.0
6:          5.4         3.9          1.7         0.4       5.4


推荐答案

我不会保证它的速度,但这至少避免了胁迫矩阵:

I won't vouch for its speed, but this at least avoids coercing to a matrix:

data[,mymax:=do.call(pmax,.SD)]

这篇关于计算行向最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆