0

I am trying to combine multiple columns (adding the rows together) into 1 already existing column in the data frame.

It is easy if I know what columns to combine, but I would like to use a vector where this columns names are stored.

  data <- data.frame(player = c("player1", "player2", "player3", "player4", "player5"), 
                     attack = c(3, 1, 4, 5, 1),
                     defense = c(2, 4, 1, 0, 4),
                     other = c(1, 0, 1, 0, 1),
                     extras = c(3, 4, 2, 1, 4),
                     stats = c(1, 0, 1, 2, -1)) 
  column_values <- c("stats", "attack", "defense")

  data <- data  %>% 
    dplyr::mutate(stats = stats + attack + defense)

The column where things will be added to is known but the vector containing the other column names could change. So basically something like this (I know the code below does not work and is not correct, but just using to illustrate what I am trying to accomplish.) I am trying to keep some consistency in my code and using dplyr package.

column_values <-("stats", "attack", "defense")
data <- data  %>% 
    dplyr::mutate(stats = sum(column_values))
bretauv
  • 7,756
  • 2
  • 20
  • 57
miyene
  • 41
  • 7
  • 3
    `data$stats <- rowSums(data[column_values])` or with `dplyr` `data <- data %>% dplyr::mutate(stats = rowSums(.[column_values]))` – Ronak Shah Mar 30 '23 at 09:26

0 Answers0