My Coding > Software > R > R: CSV files

R: CSV files

CSV data file is one of the most common formats for storing table data. CSV file can be with header, or without header. Also it can be comma, semi-column or tab separated. Float digits can be with . or , decimal separators.

Reading from CSV file in R

In R different functions are used to read from these different types of files, which is not very optimal.

There are main function to read CSV files are:

  • read.csv(filename) - Read CSV file , separated
  • read.csv(filename, header=FALSE) - - Read CSV file , separated without header line
  • read.csv2(filename) - Read CSV file with ; separator and , as a deciaml separator
  • read.delim(filename) - Read CSV file TAB separated

But you should also remember, that other parameters can be used to adjust the format of the given CSV file in more details

Also, it is strongly recommend after reading CSV file data <- read.csv(filename) to check it with str(data) to understand what the columns name are. Some special characters from CSV in the names are substituted by dots.

Exporting data to CSV

To write CSV file use function write.csv(data, file=filename)


> coffe <- data.frame(
+ country = c("aaaa", "bbbb", "cccc", "dddd"),
+ product = c(33.3, 22.2, 44.4, 11.1),
+ percent = c(30, 20, 40, 10),
+ increas = c(F, F, T, F))
write.csv(coffe, file="coffe.csv")
#"","country","product","percent","increas"
#"1","aaaa",33.3,30,FALSE
#"2","bbbb",22.2,20,FALSE
#"3","cccc",44.4,40,TRUE
#"4","dddd",11.1,10,FALSE


Published: 2021-11-11 01:07:17

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.