【问题标题】:Merging data frames in R causes "names do not match previous names"在 R 中合并数据框会导致“名称与以前的名称不匹配”
【发布时间】:2023-03-24 20:42:02
【问题描述】:

合并 2 个数据框时出现“名称与以前的名称不匹配”错误。但是,它们都具有完全相同的名称。我把 ** 放在我定义数据框的两个地方,但它们是相同的。到底是怎么回事?谢谢!

确切错误: match.names(clabs, names(xi)) 中的错误:名称与以前的名称不匹配

corr <- function(directory, threshold = 0) {
    #store data frame that holds sulfate amount and nitrate amount that meet threshold and are complete cases
    **data <- data.frame(sulfate = numeric(0), nitrate = numeric(0))**

    #set working directory
    setwd(directory)

    #get file names
    myfiles <- list.files(pattern = "csv")

    #loop through files
    for(i in 1:332) {

        #read each file
        current_dataset <- read.csv(myfiles[i])

        #check if there are enough compelte cases to meet threshold
        if(sum(complete.cases(current_dataset)) > threshold) {

            #get complete cases
            complete_cases <- current_dataset[complete.cases(current_dataset), ]

            #add sulfate and nitrate info to table
            **data <- rbind(data, data.frame(sulfate = complete_cases$sulfate[i], nitrate = complete_cases$nitrate)[i])**
        }
    }
    #get correlation
    cor(data)
}

【问题讨论】:

  • 以下行的所有括号是否都在正确的位置? data &lt;- rbind(data, data.frame(sulfate = complete_cases$sulfate[i], nitrate = complete_cases$nitrate)[i])
  • 我第二个userNaNs评论

标签: r


【解决方案1】:

你没有给出一个可重复的例子,所以我猜,但我会尝试

...
for(i in seq_along(myfiles)) {
    #read each file
    current_dataset <- read.csv(myfiles[i])
    #check if there are enough complete cases to meet threshold
    if(sum(cc <- complete.cases(current_dataset)) > threshold) {
        #get complete cases
        complete_cases <- current_dataset[cc, ]
        #add sulfate and nitrate info to table
        data <- rbind(data, complete_cases[,c("sulfate","nitrate")])
    }
}

alldat <- lapply(myfiles,read.csv)
ccdat <- lapply(alldat,function(x) x[complete.cases(x),])
ccdat2 <- ccdat[sapply(ccdat,nrow)>threshold]
ccdat3 <- lapply(ccdat2,function(x) x[,c("sulfate","nitrate")])
final <- do.call(rbind,ccdat3)

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 2012-08-14
    • 2019-01-10
    • 2021-02-12
    • 2023-02-15
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多