Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

recoding numbers to name in loop

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 = ""))
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading