-2

I have a dataframe that shows the number of car sales in each country for years 2000 to 2020. I wish to divide sales made in each year by the original number of sales made in 2000 for each country. How would I do this?

birdbox05
  • 17
  • 4
  • 3
    [Research](https://meta.stackoverflow.com/q/261592/1422451), pick a method, and give it a try. Come back with **specific** question with attempted method. Be sure to set up a [mcve] – Parfait Jun 11 '21 at 01:35

1 Answers1

1

It is most helpful to have a reproducible example for us to use: How to make a great R reproducible example

Assuming your data looks something like:


> car_sales <- data.frame(
"country" = c("France", "France", "Germany", "Germany"),
"year" = c(2000, 2001, 2000, 2001),
"sales" = c(100, 150, 100, 75))

Then you can use data.table to quickly divide by this year 2000 number:

> car_sales <- as.data.table(car_sales)
> setorder(car_sales, "country", "year")
> car_sales[,sales_over_2000_sales:=sales/sales[1], by = country]
> car_sales
   country year sales sales_over_2000_sales
1:  France 2000   100                  1.00
2:  France 2001   150                  1.50
3: Germany 2000   100                  1.00
4: Germany 2001    75                  0.75

In tidyverse:

car_sales %>% 
   group_by(country) %>%
   mutate(divided_by_2000_sales = sales / sales[[1]])
Gabe Solomon
  • 365
  • 3
  • 12
  • 1
    You can add the tidyverse approach to your answer ` car_sales %>% group_by(country) %>% mutate(divided_by_2000_sales = sales / sales[[1]])` – jpdugo17 Jun 11 '21 at 01:53