3

I have a data frame with some variables with the same name but different values. I need to sum the values and keep the original values as a separate column.

data <- data.frame(cod = c("A", "B", "C", "A", "A", "B"),
           values = c(3, 4, 5, 1, 2, 5))
 data

 cod   Values 
 A          3
 B          4
 C          5
 A          1
 A          2
 B          5

I expect the following, where the original Values column is kept the same and the group sum is added as a new column, Values2:

> data2
 cod   Values Values2
 A          3       6
 B          4       9
 C          5       5
 A          1       6
 A          2       6
 B          5       9
Andrew Brēza
  • 7,705
  • 3
  • 34
  • 40
DR15
  • 647
  • 9
  • 17
  • 1
    Try `data$Values2 <- with(data, ave(Values, cod, FUN = sum))` or `library(dplyr); data %>% group_by(cod) %>% mutateValues2 = sum(Values))` – akrun Sep 03 '19 at 19:40
  • 1
    I tried the first one, and its work very well. Thanks – DR15 Sep 03 '19 at 19:47

1 Answers1

1

An option with base R would be

data$Values2 <- with(data, ave(Values, cod, FUN = sum))
akrun
  • 874,273
  • 37
  • 540
  • 662