Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the sum of combinations of values in 3 columns of a 5 column dataframe

Tags:

loops

dataframe

r

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


1 Answers

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
like image 100
Sotos Avatar answered Jan 01 '26 04:01

Sotos