Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the unemployment levels of Austria between 2006 and 2012. I would like to subtract the unemployment of each year with the year 2008 as a first step. Second i would like also to subtract the unemployment of each year with the average of the first three years combined (2006, 2007, 2008). Is there an elegant way and a short way to do it?

Here is my data:

structure(list(cntry = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L
), .Label = "Austria", class = "factor"), unemp = c(5.2, 4.9, 
4.1, 5.3, 4.8, 4.6, 4.9), year = 2006:2012), row.names = c(NA, 
-7L), groups = structure(list(cntry = structure(1L, .Label = "Austria", class = "factor"), 
    .rows = structure(list(1:7), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = 1L, class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
793 views
Welcome To Ask or Share your Answers For Others

1 Answer

here is a possibility using dplyr:

mydata %>% 
  mutate(
    unemp2 = unemp - unemp[year == 2008],
    unemp3 = unemp - mean(unemp[1:3])
    )

# A tibble: 7 x 5
# Groups:   cntry [1]
  cntry   unemp  year unemp2  unemp3
  <fct>   <dbl> <int>  <dbl>   <dbl>
1 Austria   5.2  2006    1.1  0.467 
2 Austria   4.9  2007    0.8  0.167 
3 Austria   4.1  2008    0   -0.633 
4 Austria   5.3  2009    1.2  0.567 
5 Austria   4.8  2010    0.7  0.0667
6 Austria   4.6  2011    0.5 -0.133 
7 Austria   4.9  2012    0.8  0.167 

The column unemp2 is unemployment rate minus the unemployment rate of the year 2008.

The column unemp3 is the unemployment rate minus the average unemployment rate of the first three years.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...