0

My question is confusing. But, this is what I would like to do: Let's say I have a 10 data file in my current directory such as data-01, data-02, data-03, data-04 till data-10. Each of these data file have few hundred rows with 4 fields. I would like to add new column name "ID" and keep its ID like 01 (for data file "data-01") for all the rows in that file.

Many thanks in advanced.

1
  • 2
    I usually do library(data.table); LF = list.files(pattern="csv$"); rbindlist(lapply(setNames(LF,LF), fread), idcol = "source") if the fields are the same across the files. This stacks the data and makes a "source" column containing the file name associated with each row.
    – Frank
    Jul 11, 2016 at 17:36

1 Answer 1

2

A base R solution using a loop would go like this:

df<- c()
for (x in list.files(pattern="*.csv")) {
  u<-read.table(x)
  u$Label = factor(x)
  df <- rbind(df, u)
  cat(x, "\n ")
}

This depends on your data files having the same number of columns (though you get get around that inside the loop by selecting which columns you need before rbind) and then you can set whichever filetype you are looking at. The cat is useful because you can better trace read problems (because there are always problems). I bet there is a better way to do this with apply as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.