Search code examples
rfor-loopmutate

How can I use a for loop with mutate() to calculate growth in phone numbers per year in R using the WorldPhones dataset?


Using a for loop in combination with the mutate() function to determine the growth in the number of phones used per year in R, using the WorldPhones dataset.

I am aware that there are likely more succint ways to get this information but this is part of a practical for uni and I have to use the function and loop.

Here I set up my data frame from the dataset after loading it in:

library(tidyverse)
WorldPhones <- datasets::WorldPhones

WorldPhones_df <- as.data.frame(WorldPhones)
WorldPhones_df <- WorldPhones_df %>% 
  mutate(Year = rownames(WorldPhones_df))

WorldPhones_df <- WorldPhones_df %>% 
  gather(key = "Region", value = "Phones", 1:7)
WorldPhones_df

WPSumByYear <- WorldPhones_df %>% group_by(Year) %>% summarise(sum(Phones))

Up until here all is going well, but I am struggling to get it into a for loop that also uses the mutate function to measure the growth by year.

What I tried:

growths <- c(0)
for (i in 2:length(sa_df$Year)){
  growth <- (WPSumByYear$Phones[i-1]- WPSumByYear$Phones[i])
  growths <- c(growths, growth)
}

Any advice appreciated!


Solution

  • Are you just looking for lag?

    library(tidyverse)
    
    WPSumByYear <- WorldPhones_df %>% group_by(Year) %>% summarise(Phones = sum(Phones))
    
    WPSumByYear |>
      mutate(growth = Phones - lag(Phones))
    #> # A tibble: 7 x 3
    #>   Year  Phones growth
    #>   <chr>  <dbl>  <dbl>
    #> 1 1951   74494     NA
    #> 2 1956  102199  27705
    #> 3 1957  110001   7802
    #> 4 1958  118399   8398
    #> 5 1959  124801   6402
    #> 6 1960  133709   8908
    #> 7 1961  141700   7991