19

300 個の .csv ファイルを結合する次の関数を作成しました。私のディレクトリ名は「specdata」です。実行のために次の手順を実行しました。

x <- function(directory) {     
    dir <- directory    
    data_dir <- paste(getwd(),dir,sep = "/")    
    files  <- list.files(data_dir,pattern = '\\.csv')    
    tables <- lapply(paste(data_dir,files,sep = "/"), read.csv, header = TRUE)    
    pollutantmean <- do.call(rbind , tables)         
}

# Step 2: call the function
x("specdata")

# Step 3: inspect results
head(pollutantmean)

Error in head(pollutantmean) : object 'pollutantmean' not found

私の間違いは何ですか?誰でも説明できますか?

4

6 に答える 6

48

関数に不要なコードがたくさんあります。次のように単純化できます。

load_data <- function(path) { 
  files <- dir(path, pattern = '\\.csv', full.names = TRUE)
  tables <- lapply(files, read.csv)
  do.call(rbind, tables)
}

pollutantmean <- load_data("specdata")

do.call+rbindは比較的遅いことに注意してください。dplyr::bind_rowsまたはdata.table::rbindlistが大幅に高速になる可能性があります。

于 2014-04-21T13:04:12.260 に答える
5

これは、tidyverse の dplyr と purrr を使用して非常に簡潔に行うことができます。x は、簡単に使用できる csv ファイルの名前のリストです。

bind_rows(map(x, read.csv))

read.csv を x にマッピングすると、bind_rows が適切に結合する dfs のリストが生成されます!

于 2018-05-31T12:43:45.973 に答える
-1

現在の関数pollutantmeanでは、関数のスコープでのみ使用できますx。関数をこれに変更します

x <- function(directory) { 

    dir <- directory

    data_dir <- paste(getwd(),dir,sep = "/")

    files  <- list.files(data_dir,pattern = '\\.csv')

    tables <- lapply(paste(data_dir,files,sep = "/"), read.csv, header = TRUE)

    assign('pollutantmean',do.call(rbind , tables))

}

assignの結果をグローバル環境でdo.call(rbind, tables)呼び出される変数に入れる必要があります。pollutantmean

于 2014-04-21T03:28:10.503 に答える