if()参数中的错误在R中的长度为零 [英] error in if() argument is of length zero in R

查看:1451
本文介绍了if()参数中的错误在R中的长度为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码

`

region<-阿灵顿"

region<-"ARLINGTON"

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

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

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

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

if(grep(region,as.character(data [[3]] [i]),ignore.case = TRUE)== 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)
  }   
}

} `

现在我要在这里执行的操作是访问csv的列(第3个)并将其与指定的区域进行比较!我不断收到错误消息

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

if(grep(region,as.character(data [[3]] [i]),ignore.case = TRUE)==时发生错误:

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

参数的长度为零

推荐答案

详细说明我的评论和@Adii_的内容:

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

使用grep时,结果是满足条件的元素的位置" ...如果没有匹配项,则结果为无"(因此出现错误消息).

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

使用grepl,您将获得TRUE或FALSE,可在if语句中使用.

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

对于length(grep(...)),如果不匹配,结果将为0,与if语句的FALSE相对应,或者为正整数(在您的情况下为1,因为您正在测试(只有一个元素)(如果存在匹配项),对应于if语句的TRUE.

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.

这篇关于if()参数中的错误在R中的长度为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆