Reputation: 12683
I have a data frame with 3 columns,
I would like to merge the 2 columns with the bigger value into one with the sum.
Function should throw an error whenever a merge is not possible. (e.g: when there's a tie on smaller value 0.3,0.3,0.4)
E.g
|A| |B| |C|
0.5 0.3 0.2
0.1 0.7 0.2
0.4 0.4 0.2
resulting data frame:
|X| |Y|
0.8 0.2 #(x=0.5 + 0.3)
0.9 0.1 #(x=0.7 + 0.2)
0.8 0.2 #(x=0.4 + 0.4)
Thanks in advance for your help
Update:
In case someone has the same problem, I used:
apply(dt, 1, function(x) which(x==min(x)))
to find if there are 2 same minimum values in the data frame
Upvotes: 1
Views: 171
Reputation: 12875
dt$something <- dt$A + dt$B + dt$C - pmin(dt$A,dt$B,dt$C)
Your extra condition is easier to handle with a data.table
dt <- data.table(dt)
dt[,something := A + B + C - pmin(A,B,C) ]
dt[A==B | B ==C | C==A,something := NA]
Upvotes: 3
Reputation: 193517
Perhaps something like this will get you off to a start:
t(apply(mydf, 1, function(x) {a <- sort(x); c(sum(a[2:3]), a[1])}))
# [,1] [,2]
# [1,] 0.8 0.2
# [2,] 0.9 0.1
# [3,] 0.8 0.2
You'll need to add your other conditions in though.
Upvotes: 1