NA列之间的相关性

时间:2014-01-20 17:09:17

标签: r function for-loop correlation

我必须编写一个函数,它接受数据文件目录和完整案例的阈值,并计算每个文件中硫酸盐和硝酸盐(两列)之间的相关性,其中完全观察到的案例数(在所有变量上)是大于门槛。该函数应返回满足阈值要求的监视器的相关向量。如果没有文件满足阈值要求,则该函数应返回长度为0的数字向量。此函数的原型如下

我的代码看起来像这样

corr <- function(directory,threshold=0){
    a<-list.files("specdata")
    for (i in a) {
        data <- read.csv(paste(directory, "/", i, sep =""))
        x<-complete.cases(data)
        j<-sum(as.numeric(x))
        sulfate<-data[,2]
        nitrate<-data[,3]
        b<-cor(sulfate,nitrate)
    }  
    if (j>threshold) 
        return(b) 
    else
        numeric()
}

没有错误信息

如果我输入

  

z,其中; -corr( “specdata”)

     

头(z)的       [1] NA

我不知道问题是什么。我不知道列中的NA值是否与它有关。我觉得我的代码中缺少一些东西。我认为read.csv在每个文件需要一个数据帧时会创建一个唯一的数据帧,但我不明白为什么在这种情况下返回为NA(当没有阈值时)。

但是,如果我引入更大的阈值(1000):

z<-corr("specdata",1000)
head(z)
numeric(0)

我需要的预期输出是

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

2 个答案:

答案 0 :(得分:2)

this is the correct and running solution you can refer to this 

corr <- function(directory, threshold = 0) {
  ## 'directory' is a character vector of length 1 indicating the location of
  ## the CSV files

  ## 'threshold' is a numeric vector of length 1 indicating the number of
  ## completely observed observations (on all variables) required to compute
  ## the correlation between nitrate and sulfate; the default is 0

  ## Return a numeric vector of correlations
  df = complete(directory)
  ids = df[df["nobs"] > threshold, ]$id
  corrr = numeric()
  for (i in ids) {

    newRead = read.csv(paste(directory, "/", formatC(i, width = 3, flag = "0"), 
                             ".csv", sep = ""))
    dff = newRead[complete.cases(newRead), ]
    corrr = c(corrr, cor(dff$sulfate, dff$nitrate))
  }
  return(corrr)
}
complete <- function(directory, id = 1:332) {
  f <- function(i) {
    data = read.csv(paste(directory, "/", formatC(i, width = 3, flag = "0"), 
                          ".csv", sep = ""))
    sum(complete.cases(data))
  }
  nobs = sapply(id, f)
  return(data.frame(id, nobs))
}
cr <- corr("specdata", 150)
head(cr)

答案 1 :(得分:0)

这个问题可能最好分为两个步骤 - 计算每个文件的值并收集所有文件的结果。

corr.file <- function(filename) {
  data <- read.csv(paste(directory, "/", i, sep =""))
  x <- complete.cases(data)
  sulfate <- data[,2]
  nitrate <- data[,3]
  b <- cor(sulfate,nitrate)
  if (j>threshold) return(b) else return(numeric())
}

a <- list.files("specdata")
correlations <- sapply(a, corr.file)