Reputation: 117
I am trying to load a folder of large files (35million Rows Total) into R and have it as a data frame.
I have managed to load the data in, although it does take 10/15 mins to do so using the code below, however, the problem is that all the columns from the csv's are becoming 1 column. Here is my code:
# Load files
temp = list.files(path ="D:/", pattern="*.csv", full.names = TRUE)
myfiles = lapply(temp, read.delim)
# Make Dataframe
df_list = lapply(seq(length(myfiles)),function(i){
df = as.data.frame(myfiles[i], stringsAsFactors = FALSE)
})
head(do.call(bind_rows,df_list))
df = as.data.frame(data.table::rbindlist(df_list, use.names=TRUE, fill=TRUE))
The column of a csv could look like:
|A|B|C|D1|E|
However is output in my dataframe like:
|A.B.C.D1..E|
Any help with solving this maintaining columns issue would be appriciated.
Upvotes: 0
Views: 52
Reputation: 6813
You can use fread()
to read the csv faster and rbindlist()
to combine the data in the lists. Both come from the data.table
package.
library(data.table)
# Load files
temp = list.files(path ="D:/", pattern="*.csv", full.names = TRUE)
Use fread()
instead of read.delim()
:
myfiles = lapply(temp, fread)
Since no reproducible data is provided:
df_list <- lapply(1:5, function(x) {
set.seed(x)
rows <- sample(1:32, 2)
mtcars[rows, ]
})
Combine the data in the lists:
df <- rbindlist(df_list)
This is the result:
mpg cyl disp hp drat wt qsec vs am gear carb
1: 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
2: 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
3: 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
4: 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
5: 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
6: 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
7: 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
8: 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
9: 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
10: 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
Upvotes: 1