0

I have a dataset (popdata) with 2 variables (STATE and COUNTY, for the state fips code and county fips code) that I needed to transform into a new variable (county_fips_code) that matches the formatting of the county fips code in another dataframe so I can join them (a 5 digit county FIPs code made up of a 2 digit state code + a 3 digit county code).

I created new reformatted variables for both the state and county codes to get the right leading zeros and then pasted them together to create the new variable. It mostly worked, but after I paste the leading zero for state codes that were originally only 1 digit disappears. Any ideas how to paste the reformatted state and county codes together without losing the leading zero on the state code? Sorry this isn't explained very well, I'm a new R user!

is.character(popdata$STATEreformat) #TRUE 
is.character(popdata$COUNTYreformat) #TRUE 

#Create new STATE and COUNTY variables in popdata that are padded with zeros
popdata$STATEreformat <- with(popdata, ifelse(nchar(STATE) == 1, str_c(0,STATE), STATE)) #if 1 digit in state, add 1 leading zero
popdata$COUNTYreformat <- with(popdata, ifelse(nchar(COUNTY) == 1, str_c("00",COUNTY), COUNTY)) #if 1 digit in county, add 2 leading zeros
popdata$COUNTYreformat <- with(popdata, ifelse(nchar(COUNTY) == 2, str_c(0,COUNTY), COUNTYreformat)) #if 1 digit in county, add 2 leading zeros

#Merge STATEreformat and COUNTYreformat variables in popdata into a single new variable
popdata$county_fips_code <- paste(popdata$STATEreformat, popdata$COUNTYreformat,sep="")
r2evans
  • 141,215
  • 6
  • 77
  • 149
valeriek
  • 31
  • 1
  • 1
  • 2

0 Answers0