error in if() argument is of length zero in R

寵の児 提交于 2020-01-07 08:26:08

问题


This is the code

`

region<-"ARLINGTON"

data<-read.csv("city_markets.csv")

for(i in 1:length(data[[1]])){

if(grep(region,as.character(data[[3]][i]),ignore.case=TRUE)==1){

for(j in 1:length(data)){
    write(data[[j]][i],"analyzed.txt",append=TRUE)
  }   
}

} `

now what i'm trying to do here is I'm accessing the csv's column(3rd one) and comparing it with the region specified! i keep getting the error

Error in if (grep(region, as.character(data[[3]][i]), ignore.case = TRUE) == :

argument is of length zero


回答1:


To detail a bit my comment and @Adii_ 's :

when you use grep, the result is the "position" of elements that fulfill the condition... so "nothing" if there is no match (hence the error message).

Using grepl, you'll get TRUE or FALSE, which you can use in your if statement.

As for length(grep(...)), the result will be 0 if there is no match, corresponding to FALSE for the if statement, or a positive integer (1 in your case because you're testing only one element), if there is a match, corresponding to TRUE for the if statement.




回答2:


this solved my problem:

region<-"ARLINGTON"

data<-read.csv("city_markets.csv")

for(i in 1:length(data[[1]])){

a<-as.character(data[[3]][i])

if(grepl(region,a,ignore.case=TRUE)){
for(j in 1:length(data)){
    write(data[[j]][i],"analyzed.txt",append=TRUE)
  }   
}

} `


来源:https://stackoverflow.com/questions/27015180/error-in-if-argument-is-of-length-zero-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!