Sir_Maverick
Sir_Maverick

Reputation: 3

How to summarize data by row and column in R

I have the following problem. I have a table with data as below:

enter image description here

and want to create a summary that looks like that:

enter image description here

In Excel it matter of simple pivot table, but how to do it in R?

Upvotes: 0

Views: 137

Answers (1)

amallik
amallik

Reputation: 71

library(dplyr)
cardata <- data.frame(country = c("poland", "germany", "austria",
                              "poland","poland", "austria",
                              "germany","germany"),
                  car = c("Fiat", "Fiat", "BMW", "Fiat", "BMW",
                          "Toyota", "Toyota", "Toyota"),
                  Age = c(5, 4, 2, 6, 6, 2, 1, 8),
                  Km = c(12e4, 10e4, 22e3, 14e4, 15e4, 52e3, 21e3, 22e4))

cardata %>%
group_by(country, car) %>%
summarise(AvgAge = mean(Age),
          AvgKm = mean(Km))

Upvotes: 1

Related Questions