Max of sum of combinations across columns in a dataframe

Viewed 84

I have the dataframe

df <- data.frame(e_1=c(1,2,3,4,5), e_2=c(1,3,5,7,9), e_3=c(2,4,6,8,1),
                e_4=c(1,2,4,5,7), e_5=c(1,8,9,6,4), Lanes=c(3,4,3,5,4))

I try to use:

max(combn(df[,(1:5)],df$Lanes,FUN = function(i) rowSums(df[,(1:5)][i])))

I get the error

Error in combn(df[, (1:5)], df$Lanes, FUN = function(i) rowSums(df[, (1:5)][i])) : length(m) == 1L is not TRUE

3 Answers

I guess you can try using combn row-wise, e.g.,

df$comb <- apply(df,1,function(v) max(combn(v[1:5],v["Lanes"],sum)))

such that

> df
  e_1 e_2 e_3 e_4 e_5 Lanes comb
1   1   1   2   1   1     3    4
2   2   3   4   2   8     4   17
3   3   5   6   4   9     3   20
4   4   7   8   5   6     5   30
5   5   9   1   7   4     4   25

Using dplyr and purrr for this one could look as follows.

library(dplyr)
library(purrr)
library(rlang)

df <- data.frame(e_1=c(1,2,3,4,5), e_2=c(1,3,5,7,9), e_3=c(2,4,6,8,1),
                 e_4=c(1,2,4,5,7), e_5=c(1,8,9,6,4), Lanes=c(3,4,3,5,4))

df %>%
  mutate(eSum = pmap(list(!!!parse_exprs(colnames(.))),
                     ~ max(colSums(combn(c(..1, ..2, ..3, ..4, ..5), ..6)))))

#   e_1 e_2 e_3 e_4 e_5 Lanes eSum
# 1   1   1   2   1   1     3    4
# 2   2   3   4   2   8     4   17
# 3   3   5   6   4   9     3   20
# 4   4   7   8   5   6     5   30
# 5   5   9   1   7   4     4   25

An option with c_across from dplyr

library(dplyr)
df %>% 
    rowwise %>% 
    mutate(Comb = max(combn(c_across(starts_with('e')), Lanes, FUN = sum)))
# A tibble: 5 x 7
# Rowwise: 
#    e_1   e_2   e_3   e_4   e_5 Lanes  Comb
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1     1     2     1     1     3     4
#2     2     3     4     2     8     4    17
#3     3     5     6     4     9     3    20
#4     4     7     8     5     6     5    30
#5     5     9     1     7     4     4    25
Related