未定义的列选择 v. 不允许重复 'row.names'

Undefined Columns Selected v. duplicate 'row.names' are not allowed

在一个 for 循环中,我试图 运行 我的数据框中两列数据之间的一个函数,并在每次循环交互时移动到另一个数据集。我想将 for 循环的每个输出输出到一个答案向量中。

我无法通过以下错误(在我的代码下方列出),具体取决于我是否将 row.names = NULL 添加或删除到 data <- read.csv。 .. 以下代码的一部分(for 循环的第 4 行):

** 编辑以包含目录引用,最终错误是:

corr <- function(directory, threshold = 0) {
  source("complete.R")

上面的代码/我看不见的目录组织是我的错误所在

  lookup <- complete("specdata")
  setwd(paste0(getwd(),"/",directory,sep=""))
  files <-list.files(full.names="TRUE") #read file names
  len <- length(files)   
  answer2 <- vector("numeric") 
  answer <- vector("numeric")
  dataN <- data.frame()
      for (i in 1:len) {
          if (lookup[i,"nobs"] > threshold){
               # TRUE -> read that file, remove the NA data and add to the overall data frame
               data <- read.csv(file = files[i], header = TRUE, sep = ",")
               #remove incomplete
               dataN <- data[complete.cases(data),]
               #If yes, compute the correlation and assign its results to an intermediate vector.

        answer<-cor(dataN[,"sulfate"],dataN[,"nitrate"])
        answer2 <- c(answer2,answer)
      }
    }

setwd("../") return(answer2) }

1) read.table(file = file, header = header, sep = sep, quote = quote, : 不允许重复 'row.names'

对)

2) [.data.frame(data, 2:3) 中的错误:选择了未定义的列

我试过的

  1. 直接引用列名"colA"
  2. 在 for 循环之前将 data 和 dataN 初始化为空 data.frames
  3. 正在将 answer2 初始化为空向量
  4. 更好地了解向量、矩阵和 data.frames 如何相互配合

** 谢谢!**

一种方法:

# get the list of file names
files <- list.files(path='~',pattern='*.csv',full.names = TRUE)

# load all files
list.data <- lapply(files,read.csv, header = TRUE, sep = ",", row.names = NULL)

# remove rows with NAs
complete.data <- lapply(list.data,function(d) d[complete.cases(d),])

# compute correlation of the 2nd and 3rd columns in every data set
answer <- sapply(complete.data,function(d) cor(d[,2],d[,3]))

想法相同,实现略有不同

cr <- function(fname) {
    d <- read.csv(fname, header = TRUE, sep = ",", row.names = NULL)
    dc <- d[complete.cases(d),]
    cor(dc[,2],dc[,3])
}
answer2 <- sapply(files,cr)

CSV 文件示例:

# ==> a.csv <==
#     a,b,c,d
# 1,2,3,4
# 11,12,13,14
# 11,NA,13,14
# 11,12,13,14
# 
# ==> b.csv <==
#     A,B,C,D
# 101,102,103,104
# 101,102,103,104
# 11,12,13,14

我的问题是我在上面的代码中引用了函数 .R 文件,它与我循环访问和分析的数据文件位于同一目录中。我的 "files" 向量长度不正确,因为它正在读取我在函数前面创建和引用的另一个 .R 函数。我相信这个 R 文件是创建 'undefined columns'

的原因

抱歉,我什至没有在问题所在的地方放置正确的代码区域。

要点:您始终可以在函数内的目录之间移动!事实上,如果你想对感兴趣的目录的所有内容执行一个功能,这可能是非常必要的