user4999605
user4999605

Reputation: 441

finding min values between rows in R (dplyr)

I have this data frame in R, where the sum column is the sum of V1 and V2, what I would like to do is use the mutate function (in dplyr) to create a new column (V4) that takes the MIN value between V1 and V2 and divides it by the sum.

   V1 V2 sum   
1  2  3  5  
2  2  4  6   
3  1  4  5  
4  5  3  8   
5  5  3  8   
6  3  2  5   

this is what I would like it to look like in the end

  V1 V2 sum V4  
1  2  3  5  .4
2  2  4  6  .33
3  1  4  5  .2
4  5  3  8  .375
5  5  3  8  .375
6  3  2  5  .4 

Or if you know another easier way that would be greatly appreciated. Thank you!

Upvotes: 0

Views: 1854

Answers (3)

I.Eskw
I.Eskw

Reputation: 1

R basic solution:

within(df, {sum=V1+V2; V4=pmin(V1,V2)/sum})

Upvotes: 0

dimitris_ps
dimitris_ps

Reputation: 5951

Or use pairwise min

df <- data.frame(V1=c(2, 2, 1, 5, 5, 3),
             V2=c(3, 4, 4, 3, 3, 2))

library(dplyr)

df %>% mutate(sum=V1+V2, V4=pmin(V1, V2)/sum)

Upvotes: 8

cdeterman
cdeterman

Reputation: 19970

You are looking for the rowwise function in dplyr

library(dplyr)

df %>%
    rowwise() %>%
    mutate(V4 = min(V1, V2)/sum)

Source: local data frame [6 x 4]
Groups: <by row>

  V1 V2 sum        V4
1  2  3   5 0.4000000
2  2  4   6 0.3333333
3  1  4   5 0.2000000
4  5  3   8 0.3750000
5  5  3   8 0.3750000
6  3  2   5 0.4000000

Upvotes: 5

Related Questions