Joe
Joe

Reputation: 41

"else if" statement in R

Newbie to R and came across a problem. I'm pulling in excel sheets from HUD and built a function for preforming a bunch of manipulations to the sheet. However they change the name of the FIPS column beginning in 2012. So i just wanted to say

if(2013-2015) {do this}
   else if(2009-2012) {do this other thing}

what bugs me is that this works perfectly fine for the 2013-2015, but I get an error message when it hits the "else if" portion for 2012. My code is below:

library(gdata)#requires latest version of perl be downloaded
library(dplyr)

r<-function(ws,y){

library(dplyr)
df<-read.xls(ws)

if(y==2015||2014||2013){

  df$fips2010<-gsub(99999,"",df$fips2010)
  df<-df[nchar(df$fips2010)<=5,]
  #adding a zero in front of all FIPS obs. with 4 characters 
  df[nchar(df[,1])==4,1] <- paste("0", df[nchar(df[,1])==4,1], sep="")
  df<-mutate(df,Year=y)
  #filtering out puerto rico
  df<-df[-grep("^72",df$fips2010),]
  df$Year_FIPS<-paste(df$Year,df$fips2010,sep="_")
  df<-select(df,Year_FIPS,cty_hud=countyname,st_hud=state_alpha,"3bdr_hud"=fmr3)

 return(df)

 } else if (y==2012||2011||2010||2009){

  df$FIPS<-gsub(99999,"",df$FIPS)
  df<-df[nchar(df$FIPS)<=5,]
  #adding a zero in front of all FIPS obs. with 4 characters 
  df[nchar(df[,1])==4,1] <- paste("0", df[nchar(df[,1])==4,1], sep="")
  df<-mutate(df,Year=y)
  #filtering out puerto rico
  df<-df[-grep("^72",df$FIPS),]
  df$Year_FIPS<-paste(df$Year,df$FIPS,sep="_")
  df<-select(df,Year_FIPS,cty_hud=countyname,st_hud=state_alpha,"3bdr_hud"=fmr3)

return(df)
} 
}

r13<-r(ws = "http://www.huduser.org/portal/datasets/fmr/fmr2013f/FY2013_4050_Final.xls",
   y="2013")

r12<-r(ws = "http://www.huduser.org/portal/datasets/fmr/fmr2012f/FY2012_4050_Final.xls",
   y="2012")

Upvotes: 1

Views: 234

Answers (1)

kasterma
kasterma

Reputation: 4469

The error in the code seems to be (as @nicola pointed out in a comment) that y==2015||2014||2013 is always true. The intention is presumably (also verified in a comment) to check membership, e.g. replace it by

y %in% c(2015,2014,2013)

Upvotes: 1

Related Questions