0

I have a dataframe like the following in R:

df <- matrix(c('A','A','A','A','B','B','B','B','C','C','C','C',4,6,8,2,2,7,2,8,9,1,2,5),ncol=2)

For each row of this dataframe, I want to include the total value for each class (A,B,C) so that the dataframe will look this this:

df <- matrix(c('A','A','A','A','B','B','B','B','C','C','C','C',4,6,8,2,2,7,2,8,9,1,2,5,20,20,20,20,19,19,19,19,17,17,17,17),ncol=3)

What's a way I could accomplish this?

Thanks in advance for your help.

  • You have matrices, not data frames (because you explicitly use the `matrix()` function). You probably do want to have data frames, because a matrix can only hold one data type, but a data frame can hold a different data type in each column. – Gregor Thomas Dec 20 '21 at 20:50
  • Once you have your data in a data frame, you should be able to use any of the answers at the linked FAQ to add your new column. Using `dplyr` and starting with your matrix you can do `library(dplyr); df %>% as.data.frame %>% group_by(V1) %>% mutate(V2 = as.numeric(V2), total = sum(V2))` – Gregor Thomas Dec 20 '21 at 20:52

2 Answers2

0

A dplyr solution would be this:

data.frame(df) %>%
  group_by(X1) %>%
  mutate(Sum = sum(as.numeric(X2)))
# A tibble: 12 × 3
# Groups:   X1 [3]
   X1    X2      Sum
   <chr> <chr> <dbl>
 1 A     4        20
 2 A     6        20
 3 A     8        20
 4 A     2        20
 5 B     2        19
 6 B     7        19
 7 B     2        19
 8 B     8        19
 9 C     9        17
10 C     1        17
11 C     2        17
12 C     5        17
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
0

Using R base

df <- data.frame(df)
df$Total <-  ave(as.numeric(df$X2), df$X1, FUN=sum)
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138