简体   繁体   English

R中的“ else if”语句

[英]“else if” statement in R

Newbie to R and came across a problem. R的新手,遇到了一个问题。 I'm pulling in excel sheets from HUD and built a function for preforming a bunch of manipulations to the sheet. 我从HUD中提取了Excel工作表,并构建了一个功能,用于对工作表执行一堆操作。 However they change the name of the FIPS column beginning in 2012. So i just wanted to say 但是他们从2012年开始更改FIPS列的名称。所以我只想说

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: 让我感到烦恼的是,这对于2013-2015来说效果很好,但是当它在2012年达到“ else if”部分时,我收到一条错误消息。我的代码如下:

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

The error in the code seems to be (as @nicola pointed out in a comment) that y==2015||2014||2013 is always true. 代码中的错误似乎(如@nicola在注释中指出) y==2015||2014||2013始终为true。 The intention is presumably (also verified in a comment) to check membership, eg replace it by 意图(可能也在注释中得到了验证)用于检查成员资格,例如将其替换为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM