Question

I have a directory that contains lets say two .csv files, that i want to read and import into R.

So far i have tried the code below that actually works. But only for one of the files.

for (i in list.files(path = ".", pattern = "\\.csv$")){
    print(i)
    f <- read.table(i, fill=TRUE, row.names=NULL)
    Table <- data.frame(f[3])
    Table["station.id"] <- i
}
Table

Produces

      V3 station.id
1   8.27  agrin.csv
2   9.11  agrin.csv
3  11.60  agrin.csv
4  15.30  agrin.csv
5  20.53  agrin.csv
6  25.07  agrin.csv
7  27.42  agrin.csv
8  27.11  agrin.csv
9  22.92  agrin.csv
10 17.98  agrin.csv
11 13.15  agrin.csv
12  9.62  agrin.csv
13 17.34  agrin.csv

What i want is to implement a for loop that will iterate the dir and create a table as shown above for each file inside.

Notice that print(i) line gives back two results agrin.csv and agr.csv for example

Any suggestions?

Was it helpful?

Solution

Before the for loop, let:

 Table <- data.frame(V3=numeric(0), station.id=character(0))

This is called object preallocation. Then, in the loop, try playing with rbind. With this scheme you'll be creating your object incrementally.

OTHER TIPS

You are not specifying the row index of Table$station.id so the last value ends up being written over the whole column. Try this:

file.names <- list.files(path = ".", pattern = "\\.csv$")
Table <- data.frame(V3=rep(NA, length(file.names)), 
                    station.id=rep(NA, length(file.names)))
for (i in seq_along(file.names)){
    print(file.names[i])
    f <- read.table(file.names[i], fill=TRUE, row.names=NULL)
    Table[i, "V3"] <- f[3]     ## this only works if f has only one observation.
    Table[i, "station.id"] <- file.names[i]
}
Table
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top