I have the dataframe DATA with the first 5 rows shown:
>dput(DATA)
structure(list(e_1 = c(21.8, 21.8, 21.8, 21.8, 21.8),
e_2 = c(9.8, 9.8, 9.8, 9.8, 9.8), e_3 = c(-2.2, -2.2, -2.2,
-2.2, -2.2), e_4 = c(-14.2, -14.2, -14.2, -14.2, -14.2),
e_5 = c(0, 0, 0, 0, 0)), row.names = c(NA, 5L), class = "data.frame")
I want to use combn
to get the sum of all combinations of three of the columns of the dataframe across the columns. I use the following:
library(utils)
combn(DATA,3,sum)
The results are over all the rows and I get:
[1] 147 87 158 27 98 38 -33 38 -22 -82
The desired output is the same number of rows as the dataframe DATA. For each row, give the sum the values in all possible combinations of 3 of the 5 columns in DATA. such as:
[1] 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4
[11] 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4
[21] 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4
[31] 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4
[41] 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4
To apply over the rows of your df you can use apply
:
d <- structure(list(e_1 = c(21.8, 21.8, 21.8, 21.8, 21.8),
e_2 = c(9.8, 9.8, 9.8, 9.8, 9.8), e_3 = c(-2.2, -2.2, -2.2,
-2.2, -2.2), e_4 = c(-14.2, -14.2, -14.2, -14.2, -14.2),
e_5 = c(0, 0, 0, 0, 0)), row.names = c(NA, 5L), class = "data.frame")
t(apply(d, 1, combn, 3, sum))
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#> 1 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4
#> 2 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4
#> 3 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4
#> 4 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4
#> 5 29.4 17.4 31.6 5.4 19.6 7.6 -6.6 7.6 -4.4 -16.4