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?
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.
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.
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.
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.
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)))
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