Home > Software design >  Convert list of years into another series of numbers R
Convert list of years into another series of numbers R

Time:01-14

I have a series of years 2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014. I want to convert them into a series 1, 2, 3, 4, 5, 6 in R. The most recent year is number one, and I want anything that's 6 or more years ago to be grouped into one item. This will then be stored as a column in the data with a mutate clause.

I have already calculated the latest year and saved it as a variable, Latest_Yr.

Latest_Yr <- data %>%
  (summarise(max(Full_year))

data %>%
  mutate(Yr_Sqnce = ((Latest_Yr - Full_year)   1)) %>%
  ifelse(select_data$Yr_Sqnce <6, Yr_Sqnce, "6 ")

I try to run the mutate but get

Error in `[.data.table`(x, i, , ) : 
  Column 7 ['Yr_Sqnce'] is a data.frame or data.table; malformed data.table.

I've tried as.integer in front of the summarise and just the max(), but they're giving an error. So, how do I make it store the number as an integer, not a table, so I can calculate my list?

CodePudding user response:

Is this kind of what you are looking for? I'm unsure what data looks like, so I just created a minimal example here. You don't need to get the max ahead of time; you can just use max in a mutate statement to calculate the new numbers. Then, I used an ifelse inside of mutate to replace the 6 values.

library(tidyverse)

df %>% 
  mutate(group = (max(year) - year) 1), 
         group = ifelse(group >= 6, "6 ", group))

Output

  year group
1 2021     1
2 2020     2
3 2019     3
4 2018     4
5 2017     5
6 2016    6 
7 2015    6 
8 2014    6 

Data

df <-
  structure(list(year = c(
    2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014
  )),
  class = "data.frame",
  row.names = c(NA,-8L))

CodePudding user response:

Shouldn't it be

ifelse(select_data$Yr_Sqnce <6, select_data$Yr_Sqnce, "6 ")
  •  Tags:  
  • Related