I have a dataframe:
df <- data.frame(a=c(1,2), b=c(3,4), c=c(3,5), d=c(6,5), e=c(9,2))
I want to write a function that gives me all the possible combinations of the 3 of the column values. The desired output would be
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 7 10 13 10 3 16 12 15 18 18
2 11 11 8 12 9 9 14 11 11 12
I would like to write a loop that would go through the different combinations of the n number of the columns, which in this question n=3
One way is to use combnon the sequence of the number of columns of your data frame (i.e. 1:5 or seq(5)) and then use it as index to subset the data frame. Then rowSums() will add the values, i.e.
combn(seq_along(df), 3, FUN = function(i) rowSums(df[i]))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 7 10 13 10 13 16 12 15 18 18
[2,] 11 11 8 12 9 9 14 11 11 12
Another way of using combn (credits to @nicola):
combn(df,3,rowSums)
If you have different combinations for each row, then 1 way is to loop over the individual rows, i.e.
sapply(seq(nrow(df)), function(i) max(combn(df[i, 1:5], df$Lanes[i], sum)))
#[1] 18 16
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