Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutate to Create Minimum in Each Row

Tags:

r

dplyr

I have a question relating to creating a minimum value in a new column in dplyr using the mutate function based off two other columns.

The following code repeats the same value for each row in the new column. Is there a way to create an independent minimum for each row in the new column? I wish to avoid using loops or the apply family due to speed and would like to stick with dplyr if possible. Here's the code:

a = data.frame(runif(5,0,5))
b = data.frame(runif(5,0,5))
c = data.frame(runif(5,0,5))

y = cbind(a,b,c)

colnames(y) = c("a","b","c")

y = mutate(y, d = min(y$b, y$c))

y

The new column "d" is simply a repeat of the same number. Any suggestions on how to fix it so that it's the minimum of "b" and "c" in each row?

Thank you for your help.

like image 696
AME Avatar asked Feb 11 '16 02:02

AME


People also ask

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. The exception is summarise() , which return a grouped_df.

How do I sum rows in 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.


1 Answers

We can use pmin

y$d <- with(y, pmin(b, c))

Or

transform(y, d = pmin(b,c))

Or with dplyr

library(dplyr)
y %>%
  mutate(d = pmin(b,c))

min works columnwise, suppose if we want to use min, an option would be

y %>%
  rowwise %>% 
  mutate(d = min(unlist(c(b,c))))
like image 64
akrun Avatar answered Oct 22 '22 08:10

akrun