unomas83
unomas83

Reputation: 151

open several csv and put them in a data frame

I have several csv files in one folder. Each file represents the data of one participant. I am trying to create a function to open all the files and put them in one data frame. For the first file, the function should read the header, but not for the others. I have tried this:

files<-list.files(path="D:/r")
for(i in 1:length(files)){
if(i==1){
    matriz<-read.csv(files [i], header=TRUE)
}else{
    tmp<-read.csv(files[i],header=FALSE)
    matriz<-rbind(matrix,tmp)
}
}

However, it doesn´t work... Any idea? Thanks!

Upvotes: 1

Views: 1944

Answers (3)

rafa.pereira
rafa.pereira

Reputation: 13807

Here is a simple and fast way to read multiple data frames and bind them into a single data frame using fread

# Load library
  library(data.table)

# Get a List of all files named with a key word, say all `.csv` files
  filenames <- list.files("C:/your/folder", pattern="*.csv", full.names=TRUE)

 # Load and bind all data sets
   data <- rbindlist(lapply(filenames,fread))

Upvotes: 1

HumeMarx
HumeMarx

Reputation: 1

I had a similar error when I had not defined the matrix which I was binding to.

eg: df <- data.frame(variable=character(), x=numeric(), stringsAsFactors=FALSE)

before running the if .

for(i in 1:3000){

filename<- paste(c("Aone.txt.", i), collapse = "")
x <- read.table(filename, header=TRUE, sep=" ", row.names = NULL)
df<- rbind(df,x)    
print(i)
print(nrow(df))
}

Upvotes: 0

Eric Green
Eric Green

Reputation: 7725

Get your column names when i==1 and assign them to tmp so you can rbind().

setwd("") # your path here
files <- list.files()
for (i in 1:length(files)) {
  if (i==1) {
    matriz <- read.csv(files[i], header=TRUE)
    cname <- names(matriz)       # get column names when reading in header
  } else {
    tmp <- read.csv(files[i], header=FALSE)
    names(tmp) <- cname          # assign column names so you can bind
    matriz <- rbind(matriz,tmp)  # change error in matrix/z
  }
}

Upvotes: 1

Related Questions