Finding the maximum value for each row among 3 columns in R

前端 未结 5 430
眼角桃花
眼角桃花 2020-12-18 00:22

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

A table could be:

x = c(1,2,3,4,5 ) 
y = c(2,3,3,1,1 ) 
z = c(4,3,2,1,1 ) 
df<         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-18 01:21

    You can use the apply function for this like so:

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

    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.

提交回复
热议问题