Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rowwise maximum for R

Tags:

r

max

I have a dataframe as below. I want to get a column of maximums for each row. But that column should ignore value 9 if it is present in that row. How can i achive that efficiently?

df <- data.frame(age=c(5,6,9), marks=c(1,2,7), story=c(2,9,1)) df$max <- apply(df, 1, max)     df 
like image 242
user2543622 Avatar asked Jun 30 '14 19:06

user2543622


People also ask

How do you find the max of a row in R?

max() in R The max() is a built-in R function that finds the maximum value of the vector or data frame. It takes the R object as an input and returns the maximum value out of it. To find the maximum value of vector elements, data frame, and columns, use the max() function.

What does rowwise () do in R?

rowwise() allows you to compute on a data frame a row-at-a-time. This is most useful when a vectorised function doesn't exist. Most dplyr verbs preserve row-wise grouping.

How the last 5 rows can be extracted?

The last n rows of the data frame can be accessed by using the in-built tail() method in R. Supposedly, N is the total number of rows in the data frame, then n <=N last rows can be extracted from the structure.

How do I find the maximum of a column in R?

Maximum value of a column in R can be calculated by using max() function. Max() Function takes column name as argument and calculates the maximum value of that column.


2 Answers

Here's one possibility:

df$colMax <- apply(df, 1, function(x) max(x[x != 9])) 
like image 87
talat Avatar answered Oct 07 '22 09:10

talat


The pmax function would be useful here. The only catch is that it takes a bunch of vectors as parameters. You can convert a data.frame to parameters with do.call. I also set the 9 values to NA as suggested by other but do so using the somewhat unconventional is.na<- command.

do.call(pmax, c(`is.na<-`(df, df==9), na.rm=T)) # [1] 5 6 7 
like image 35
MrFlick Avatar answered Oct 07 '22 11:10

MrFlick