在R的3列中找到每一行的最大值 [英] Finding the maximum value for each row among 3 columns in R

查看:726
本文介绍了在R的3列中找到每一行的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算3列中每一行的最大值.

I need to calculate the maximum value for each row among 3 columns.

一个表可以是:

x = c(1,2,3,4,5 ) 
y = c(2,3,3,1,1 ) 
z = c(4,3,2,1,1 ) 
df<-data.frame(x,y,z)

我需要得到:

    x   y   z   max
1   1   2   4   4
2   2   3   3   3
3   3   3   2   3
4   4   1   1   4
5   5   1   1   5

我尝试过:

df$max<-max(x, y,z)

但是我得到了

  x y z max
1 1 2 4   5
2 2 3 3   5
3 3 3 2   5
4 4 1 1   5
5 5 1 1   5

那么,我该如何正确执行呢?

So, how can I do this correctly?

推荐答案

您可以像这样使用apply函数:

You can use the apply function for this like so:

df$max<-apply(X=df, MARGIN=1, FUN=max)

MARGIN=1参数表明,对于X中的每一行,您希望在FUN中应用该函数.如果使用MARGIN=2,则将按列显示,或者使用MARGIN = c(1,2),则将同时显示行和列.

The MARGIN=1 argument indicated that for every row in X you wish to apply the function in FUN. If you use MARGIN=2 it will be by column or MARGIN=c(1,2) it will be both rows and columns.

这篇关于在R的3列中找到每一行的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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