Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr mutate rowwise max of range of columns

Tags:

r

dplyr

I can use the following to return the maximum of 2 columns

newiris<-iris %>%  rowwise() %>%  mutate(mak=max(Sepal.Width,Petal.Length)) 

What I want to do is find that maximum across a range of columns so I don't have to name each one like this

newiris<-iris %>%  rowwise() %>%  mutate(mak=max(Sepal.Width:Petal.Length)) 

Any ideas?

like image 936
user2502836 Avatar asked Oct 06 '15 19:10

user2502836


People also ask

How do I get max of multiple columns 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. Maximum of single column in R, Maximum of multiple columns in R using dplyr.

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 do I sum across rows in R dplyr?

Syntax: mutate(new-col-name = rowSums(.)) The rowSums() method is used to calculate the sum of each row and then append the value at the end of each row under the new column name specified. The argument . is used to apply the function over all the cells of the data frame.

What does the dplyr verb mutate do?

dplyr is a grammar of data manipulation, providing a consistent set of verbs that help you solve the most common data manipulation challenges: mutate() adds new variables that are functions of existing variables. select() picks variables based on their names.


1 Answers

Instead of rowwise(), this can be done with pmax

iris %>%       mutate(mak=pmax(Sepal.Width,Petal.Length, Petal.Width)) 

May be we can use interp from library(lazyeval) if we want to reference the column names stored in a vector.

library(lazyeval) nm1 <- names(iris)[2:4] iris %>%       mutate_(mak= interp(~pmax(v1), v1= as.name(nm1))) 
like image 70
akrun Avatar answered Sep 27 '22 18:09

akrun