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
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.
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.
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.
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.
Here's one possibility:
df$colMax <- apply(df, 1, function(x) max(x[x != 9]))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With