J. Bird
J. Bird

Reputation: 25

Dividing numbers within the same variable in R

I'm trying to divide two numbers within the same column and create a new column with that figure in RStudio. Let's say my data is:

year <- c(2016, 2017, 2018, 2019, 2010)
age_group <- "16-17"
total <- c(915617, 917840, 923740, 929412, 933487)
df <- data.frame(year, age_group, total)

So my data would look like this:

Year    age_group     total
2016    16-17         915617
2017    16-17         917840
2018    16-17         923740
2019    16-17         929412
2020    16-17         933487

Essentially I'm trying to divide each of the 'total' figures from 2017, 2018, 2019 and 2020 by the original 2016 'total' figure to calculate a percent change from the baseline, with the percent change showing up in another column. I know this requires the mutate function but beyond that I'm lost. Any help would be excellent

Upvotes: 0

Views: 503

Answers (1)

schmitzi89
schmitzi89

Reputation: 65

You set a variable value:

2016_total<-total[1]

Then you can use it in the mutate formula to calculate a new column:

df_new<-df%>%
    mutate(new_column=total/2016_total)

Upvotes: 0

Related Questions