How to save a csv and read using fread in R?


To save a csv file, we can use write.csv function in R and if we want to read it using fread then fread function will be used with the name of the csv file. The benefit of reading the csv file with fread function is that there will be a variable added to the original csv file which contains the id as integers starting from 1 to the length of column values.

Consider the below data frame −

Example

 Live Demo

x<-rpois(20,5)
y<-rpois(20,5)
z<-rpois(20,5)
df<-data.frame(x,y,z)
df

Output

   x  y  z
1  8  2  4
2  2  5  4
3  5  5  3
4  7  3  9
5  3  3  7
6  1  10 6
7  5  5  3
8  4  5  3
9  5  5  2
10 8  9  7
11 6  5  6
12 8  4  3
13 6  5  10
14 4  5  3
15 4  5  7
16 6  5  6
17 6  4  6
18 2  8  7
19 6  4  3
20 8  5  6

Saving the above data frame in csv file −

write.csv(df,"FreadReadingEx.csv")

Reading the csv file using fread function −

Example

fread("FreadReadingEx.csv")

Output

    V1 x  y  z
1:  1  8  2  4
2:  2  2  5  4
3:  3  5  5  3
4:  4  7  3  9
5:  5  3  3  7
6:  6  1 10  6
7:  7  5  5  3
8:  8  4  5  3
9:  9  5  5  2
10: 10 8  9  7
11: 11 6  5  6
12: 12 8  4  3
13: 13 6  5  10
14: 14 4  5  3
15: 15 4  5  7
16: 16 6  5  6
17: 17 6  4  6
18: 18 2  8  7
19: 19 6  4  3
20: 20 8  5  6

Updated on: 10-Feb-2021

489 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements