Home > OS >  Recoding years to year nr. 0,1,2 ect
Recoding years to year nr. 0,1,2 ect

Time:12-04

I'm not very good in English or in R but hopefully I can manage to explain the problem

I have a dataset where there is one column with years, from 1952 to 2007. I want to recode and reorganize it so that the first year is number 0, the next year nr. 1 and so on...

Can anyone help me?

I have tried recode(), arrange (),

CodePudding user response:

You mean like this? :

df <- data.frame(years = 1952:2007)
is.na(df$years[sample(1:nrow(df), size = 10)]) <- TRUE

head(df)
#>   years
#> 1    NA
#> 2  1953
#> 3  1954
#> 4  1955
#> 5  1956
#> 6  1957

df$years_recoded <- df$years - min(df$years, na.rm = T)
head(df)
#>   years years_recoded
#> 1    NA            NA
#> 2  1953             0
#> 3  1954             1
#> 4  1955             2
#> 5  1956             3
#> 6  1957             4

Created on 2022-12-03 with reprex v2.0.2

CodePudding user response:

Maybe you want this: To start with 0 we have to substract 1 from row_number()

library(dplyr)

df %>% 
  mutate(year_recoded = row_number()-1) %>% 
  head()
  years year_recoded
1  1952            0
2  1953            1
3  1954            2
4  1955            3
5  1956            4
6  1957            5
  • Related