Creating mean variables using all possible combinations of the original variables in r I need to create a function that calculate the mean of all possible combinations of a given number of variables, and store the means values as separate variable and the number of variables whose means have been calculated in r.
Example of a dataset with 3 continuous variables:


Expected output:

 A: Here's a way:
dataset <- as.data.frame(matrix(nrow = 10, ncol =0))
dataset$season <- c("2011LR", "2011LR", "2012LR", "2012LR", "2013LR", "2013LR", "2014LR",
                    "2014LR", "2015LR", "2015LR")
dataset$farmer <- rep(c(107, 111), 5)
dataset$A <- c(0.87, 0.55, 0.13, 0.37, 0.07, 0.11, 1.44, 0.9, 0.45, 1.3)
dataset$B <- c(0.64, 0.52, 0.11, 0.13, 0.14, 0.02, 2.5, 0.62, 0.59, 1.28)
dataset$C <- c(0.92, 0.85, 0.64, 1.44, 0.59, 0.69, 1.58, 1.4, 0.73, 1.34)

mean_func <- function(data, varnames) {
  combinations <- list()
  for(i in 2:length(varnames)) {
    combinations <- c(combinations, combn(varnames, i, simplify = F))
  }

  output_data <- data
  length_data <- as.data.frame(matrix(nrow = nrow(output_data), ncol = 0))

  for(j in 1:length(combinations)) {
    # mean
    data_to_use <- data[,which(colnames(data) %in% combinations[[j]])]
    new_colname <- paste(unlist(combinations[[j]]), sep = "", collapse = "")
    new_col <- apply(data_to_use, 1, mean)
    output_data <- cbind(output_data, round(new_col, 2))
    colnames(output_data)[length(colnames(output_data))] <- new_colname

    # length
    length_col <- rep(length(combinations[[j]]), nrow(output_data))
    length_data <- cbind(length_data, length_col)
    colnames(length_data)[length(colnames(length_data))] <- paste(new_colname, "_len", sep = "")
  }

  output_data <- cbind(output_data, length_data)

  return(output_data)
}  

output <- mean_func(dataset, c("A", "B", "C"))
```

