0

I have a following dataframe:

brand <- as_factor(“ford”, “audi”, “ford”, “audi”)
int1 <- c(2, 3, 4, 1)
int2 <- c(5, 6, 7, 1)
int3 <- c(1, 0, 7, 8)
df <- data.frame(brand, int1, int2, int3)

I want to receive a table per factor and sum for each numeric value as this: enter image description here

For the moment I know how to do 3 separate tables:

bybrand <- tapply(df$int1, df$brand, FUN=sum)
bybrand <- tapply(df$int2, df$brand, FUN=sum)
bybrand <- tapply(df$int3, df$brand, FUN=sum)
codeforfun
  • 187
  • 10

1 Answers1

1

If you can do it in dplyr

library(dplyr, warn.conflicts = F)

df %>% group_by(brand) %>%
  summarise(across(everything(), sum))

#> # A tibble: 2 x 4
#>   brand  int1  int2  int3
#>   <fct> <dbl> <dbl> <dbl>
#> 1 audi      4     7     8
#> 2 ford      6    12     8

Created on 2021-07-24 by the reprex package (v2.0.0)

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45