Reputation: 73
The following code works in Julia, which writes the values of A
, B
, with a header.
I am questioning if there is a more elegant way to introduce the header as an option in writecsv
or writedlm
Header = ["a" "b"]
A= [1,2,3]
B=[3,4,5]
Data = [Header ; A[:] B[:]]
Path = "//OUTPUT//Table//Hydraulic_Inv.csv"
println(Path)
writecsv(Path ,Data )
the output
a,b
1,3
2,4
3,5
Upvotes: 1
Views: 3026
Reputation: 18530
Firstly, writecsv
is deprecated in v0.7, so it is probably best not to start using it now as it will be completely gone in v1.0.
Why are they getting rid of writecsv
? Because for v1.0, julia Base
is being stripped back to absolute essentials. If you need to work with csv files in v1.0, the recommended approach is to use the CSV package. For example (using Julia v1.1.1):
using CSV, DataFrames
x = [1 2 ; 3 4]
header = ["a", "b"]
CSV.write(somefilepath, DataFrame(x), header=header)
Note that in Julia v1.0 it was:
CSV.write(somefilepath, DataFrame(x), colnames=header)
It would be nice if you didn't have to wrap x
in a call to DataFrame
. I'm assuming at some point a wrapper will be put in place so that doesn't have to happen. In the meantime, it is a minor inconvenience.
If you absolutely insist on only using functions in Base
, then going forward you will need to use writedlm
. This function does not have an option for adding a header, so you basically need to do what you are currently doing, ie:
x = [1 2 ; 3 4]
header = ["a" "b"]
writedlm(somefilepath, ',', [header ; x])
Note the second argument ensures the delimiter in the written file is a comma.
Also note that this approach will almost certainly be slower (eventually) than using CSV
. This is because [header ; x]
constructs an interim temporary array of type Any
, which (as I understand things) means the subsequent write operation will be fairly inefficient. In contrast, the CSV
package tools are (will be) optimized precisely to avoid these sorts of problems, and ideally get read/write times that are compatible with reading and writing dataframes in R (ie, very fast).
Upvotes: 2
Reputation: 73
Thanks for providing so insightful answer and for explaining the future of JULIA. Just a correction of writedlm to work:
x = [1 2 ; 3 4]
header = ["a", "b"]
writedlm(somefilepath [header ; x], ",",)
Upvotes: 0