Home > Enterprise >  Creating a new variable by decades using mutate()
Creating a new variable by decades using mutate()

Time:12-02

I'm new at R and Stackoverflow, first hi, nice to met you all!

I've been trying for a while to fulfill some work but I can't, don't know if some of you could help me at this point anything is more than accepted. I tried but I keep getting nothing, for like 5h. I'm not that good at R looks like.

Thank you in advance!

This is the question:

  1. Create the new variable 'decade' from the variable year with the categories "1960s", "1970s", etc. (Remember to use case_when). Look at the sum of the GDP of the countries in the region for each decade with a bar chart.

I have to use this database

install.packages("dslabs")
library(dslabs)
gap <- tibble(dslabs::gapminder)

and this filter

g <- gap %>%
  filter(region %in% c("South America", "Central America", "Northern America", "caribbean", "Polynesia"))

Anything is welcome, really

CodePudding user response:

If I understood correctly you just went to add a "s" after year, if that's it, just use mutate()

library(dplyr)
    gap %>%
      filter(region %in% c("South America", "Central America", "Northern America", "caribbean", "Polynesia")) %>% 
      mutate(decade = paste0(year,"s"))

# A tibble: 1,482 x 10
   country      year infant_mortality life_expectancy fertility population          gdp continent region           decade
   <fct>       <int>            <dbl>           <dbl>     <dbl>      <dbl>        <dbl> <fct>     <fct>            <chr> 
 1 Argentina    1960             59.9            65.4      3.11   20619075 108322326649 Americas  South America    1960s 
 2 Belize       1960             NA              60.1      6.5       92068     86532304 Americas  Central America  1960s 
 3 Bolivia      1960            173.             43.8      6.7     3693451   3001815692 Americas  South America    1960s 
 4 Brazil       1960            129.             55.3      6.21   72493585 105343379555 Americas  South America    1960s 
 5 Canada       1960             27.8            71        3.91   17909232 167894860728 Americas  Northern America 1960s 
 6 Chile        1960            128.             56.8      5.58    7695692  14087170195 Americas  South America    1960s 
 7 Colombia     1960             89.3            58.0      6.81   16480384  19017657851 Americas  South America    1960s 
 8 Costa Rica   1960             86.5            62.0      7.31    1333042   2398494445 Americas  Central America  1960s 
 9 Ecuador      1960            121.             54.1      6.69    4545548   3641530019 Americas  South America    1960s 
10 El Salvador  1960            126.             52.0      6.73    2762897   4017741905 Americas  Central America  1960s 
  • Related