Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...