This function allows you to change the format (such as column delimiter,
decimal character) of a CSV file. It uses read.table
to read a
CSV file and write.table
to rewrite the file with modified
format to a new file. All arguments of read.table
and
write.table
are supported. Arguments that are provided by both
functions appear as two arguments <argument_name>_in
and
<argument_name>_out
in this function.
convertCsvFile(file_in, sep_in = formals(utils::read.table)$sep, sep_out = sep_in, dec_in = formals(utils::read.table)$dec, dec_out = dec_in, file_out = NULL, header = TRUE, quote_in = formals(utils::read.table)$quote, quote_out = formals(utils::write.table)$quote, row.names_in = formals(utils::read.table)$row.names, col.names_in = formals(utils::read.table)$col.names, row.names_out = FALSE, col.names_out = TRUE, fileEncoding_in = formals(utils::read.table)$fileEncoding, fileEncoding_out = fileEncoding_in, dbg = TRUE, ...)
file_in | path to input file |
---|---|
sep_in | column separator in input file |
sep_out | column separator in output file |
dec_in | decimal character in input file |
dec_out | decimal character inoutput file |
file_out | path to output file |
header | passed to |
quote_in | passed as |
quote_out | passed as |
row.names_in | passed as |
col.names_in | passed as |
row.names_out | passed as |
col.names_out | passed as |
fileEncoding_in | passed as |
fileEncoding_out | passed as |
dbg | if |
… | further arguments passed to either |
path to the created CSV file
# Write the iris dataset to a temporary file with "," as column separator csv_in <- tempfile(fileext = ".csv") write.table(iris, csv_in, row.names = FALSE) # Review the first lines of the file catLines(readLines(csv_in, 6))#> "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species" #> 5.1 3.5 1.4 0.2 "setosa" #> 4.9 3 1.4 0.2 "setosa" #> 4.7 3.2 1.3 0.2 "setosa" #> 4.6 3.1 1.5 0.2 "setosa" #> 5 3.6 1.4 0.2 "setosa"# Convert the column separator (from " " which was the default) to ";" csv_out <- convertCsvFile(csv_in, sep_out = ";")#> Reading from '/tmp/RtmpMsuQJ9/file37688438155bb.csv' ... ok. #> Writing to '/tmp/RtmpMsuQJ9/file37688438155bb_new.csv' ... ok.#> "Sepal.Length";"Sepal.Width";"Petal.Length";"Petal.Width";"Species" #> 5.1;3.5;1.4;0.2;"setosa" #> 4.9;3;1.4;0.2;"setosa" #> 4.7;3.2;1.3;0.2;"setosa" #> 4.6;3.1;1.5;0.2;"setosa" #> 5;3.6;1.4;0.2;"setosa"# Delete the file so that it can be recreated unlink(csv_out) # Convert the column separator and the decimal character csv_out <- convertCsvFile(csv_in, sep_out = ";", dec_out = ",")#> Reading from '/tmp/RtmpMsuQJ9/file37688438155bb.csv' ... ok. #> Writing to '/tmp/RtmpMsuQJ9/file37688438155bb_new.csv' ... ok.#> "Sepal.Length";"Sepal.Width";"Petal.Length";"Petal.Width";"Species" #> 5,1;3,5;1,4;0,2;"setosa" #> 4,9;3;1,4;0,2;"setosa" #> 4,7;3,2;1,3;0,2;"setosa" #> 4,6;3,1;1,5;0,2;"setosa" #> 5;3,6;1,4;0,2;"setosa"