无效的“长度"参数错误 [英] Invalid 'length' argument Error

查看:128
本文介绍了无效的“长度"参数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算一个目录中所有csv的列平均值,但是当我运行该函数时,它给我错误

I want to calculate the mean of column of all the csv in one directory, but when I run the function it give me the error of

数字(nc)中的错误:参数'length'无效".

"Error in numeric(nc) : invalid 'length' argument".

我相信CSV文件具有n/a值,但它不应该影响列数的计算吗?

I believe that CSV files have n/a value but it shouldn't affect the calculate the number of column?

pollutantmean <- function(directory, pollutant, id =1:332, removeNA = TRUE){
          nc <- ncol(pollutant)
          means <- numeric(nc)
          for(i in 1:nc){
            means[i] <- mean(pollutant[, i], na.rm = removeNA)
          }
          means
}

所以这是我的更新版本.我将R设置为使用"lapply"将所有.csv读取到一个文件中.所有这些csv文件的名称都从001到1xxx等保持一致.因此,我将ID设置为001到任何时候.

So here is my update version. I set R to read all the .csv into one file by using "lapply". All these csv files have the consistent name from 001 to 1xxx etc. So I set up the id from 001 to whenever.

files <- list.files(pattern = ".csv")
directory <- lapply(files, read.csv)
pollutantmean <- function(directory, pollutant, id =1:332, removeNA = TRUE){
  nc <- ncol(pollutant)

  means <- numeric(nc, na.rm=removeNA)

  for(i in 1:nc){

    means[i] <- mean(pollutant[, i], na.rm = removeNA)
  }
  means
}

我试图用一个文件中的所有csv计算整个目录中污染物的平均值.我打算使用"na.rm = removeNA"删除所有丢失的值.但这给了我以下错误: numerical(nc,na.rm = removeNA)中的错误:未使用的参数(na.rm = removeNA)

I tried to calcuate the mean values of pollutant accross the whole directory with all the csv in one files. I intend to remove all the missing values by using "na.rm = removeNA". But it gives me error of Error in numeric(nc, na.rm = removeNA) : unused argument (na.rm = removeNA)

推荐答案

pollutantmean <- function(directory, pollutant, id = 1:332) {
  files_list <- list.files(directory, full.names = TRUE) #creats list of files and the csv files are sitting in the directory
  dat <- data.frame() #creates empty data frame
  for(i in id){
    dat<- rbind(dat,read.csv(files_list[i])) #combin all the csv data together
  }
  good <- complete.cases(dat) #remove all the NA values from csv data set
  mean(dat[good, pollutant], na.rm = TRUE) # finally calculate mean
}

这是我的答案

这篇关于无效的“长度"参数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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