Home > Net >  recoding numbers to name in loop
recoding numbers to name in loop

Time:11-30

I have pulled in a bunch of data from the tidycensus 5-year ACS. Right now, I have a year variable that has the value for the last year of the 5-year span. I want to recode the year variable as a clearer source column. So, I want 2009 to be "acs2005_2009", 2010 to be "acs2006-2010", etc. I tried to make a loop to do this, but I just get a bunch of warnings for NAs introduced by coercion. This is basically what I am trying:

library(tidyverse)
library(dplyr)
library(purrr)

population <- sample(c(1000:9999), 10)
year <- sample(c(2009:2020), 10)

df <- data.frame(population, year)


for(x in 2009:2020){
  j <- x-4
  df <- df %>% mutate(source = recode(year, x = paste0("acs", j,"_", x), .default = ""))
}

CodePudding user response:

You can do,

df$year <- paste0('acs', df$year - 4, '_', df$year)

df
   population         year
1        6531 acs2007_2011
2        5619 acs2015_2019
3        6697 acs2016_2020
4        1203 acs2005_2009
5        4246 acs2012_2016
6        3420 acs2013_2017
7        7789 acs2014_2018
8        8631 acs2008_2012
9        3431 acs2009_2013
10       6241 acs2011_2015
  •  Tags:  
  • r
  • Related