R中的If语句出错 [英] Error in If statment in R

查看:406
本文介绍了R中的If语句出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是代码。似乎我没有设法正确定义向量'nobs','cor'并且if语句试图评估NA值。
有人能指出我的错误吗?
谢谢,
Tamir

below is the code. It seems I have not managed to define the vectors 'nobs', 'cor' correctly and the if statement is trying to asses an NA value. Can someone point me my error? Thanks, Tamir

corr<-function(directory, threshold=0){

allfiles<-list.files("specdata", full.names = TRUE)
NumOfFiles<-length(allfiles)

n<-1
id<-vector()
nobs<-vector()
cor<-vector()

for (i in NumOfFiles){
    data<-read.csv(allfiles[i])
    cleandata<-data[complete.cases(data),]
    id[n]=i
    nobs[n]<-sum(complete.cases(data))  #Number of completre cases
    n<-n+1


 if (nobs[n]>threshold){
     cor[n]<-cor(cleandata[sulfate],cleandata[nitrate])
     }
}

 return(cor)

}

推荐答案

代码并不遥远。我改变了 n< - n + 1 的位置。在您的示例中,它在函数中过早递增。当函数下降到 if(nobs [n]> threshold)时,它检查你做了n + 1,所以总是 NA

The code wasn't that far off. I changed the position of n <- n+1. In your example, it was incrementing too early in the function. When the function got down to if(nobs[n]>threshold) it was checking AFTER you did n+1, so it was always NA.

其次,我在污染物名称周围加上引号。

Secondly, I put quotes around the pollutant names.

corr<-function(directory, threshold=0){

allfiles<-list.files("specdata", full.names = TRUE, pattern="csv")
NumOfFiles<-length(allfiles)

n<-1
id<-vector()
nobs<-vector()
cor<-vector()

for (i in 1:NumOfFiles){
    data<-read.csv(allfiles[i])
    cleandata<-data[complete.cases(data),]
    id[n]=i
    nobs[n]<- sum(complete.cases(data))  #Number of completre cases

    if (nobs[n]>threshold){
      cor[n]<-cor(cleandata[,"sulfate"],cleandata[,"nitrate"])
      n<-n+1
      }

}

 return(cor)
}

我们可以测试:

summary(corr("specdata"))
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
-1.00000 -0.05205  0.10840  0.13800  0.27890  1.00000 

cr <- corr("specdata", 150)
head(cr)
[1] -0.01895754 -0.14051254 -0.04389737 -0.06815956
[5] -0.12350667 -0.07588814

其中两个匹配期望输出。

Which both match the desired output.

这篇关于R中的If语句出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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