[R] Maintaining Column names while writing csv file.

Rolf Turner rolf.turner at xtra.co.nz
Thu Jul 19 10:10:36 CEST 2012


On 19/07/12 18:55, Vincy Pyne wrote:
> Dear R helpers,
>
> I have one trivial problem while writing an output file in csv format.
>
> I have two dataframes say df1 and df2 which I am reading from two different csv files.
>
> df1 has column names as date, r1, r2, r3 while the dataframe df2 has column names as date, 1w, 2w.
>
> (the dates in both the date frames are identical also no of elements in each column are equal say = 10).
>
> I merge these dataframes as
>
> df_new = merge(df1, df2, by = "date", all = T)
>
> So my new data frame has columns as
>
> date, r1, r2, r3, 1w, 2w
>
> However, if I try to write this new dataframe as a csv file as
>
> write.csv(data.frame(df_new), 'df_new.csv', row.names = FALSE)
>
> The file gets written, but when I open the csv file, the column names displayed are as
>
> date, r1, r2, r3, X1w, X2w
>
> My original output file has about 200 columns so it is not possible to write column names individually. Also, I can't change the column names since I am receiving these files from external source and need to maintain the column names.

Just omit the unnecessary and redundant call to data.frame()
inside your call to write.csv().  I.e. just do:

write.csv(df_new, 'df_new.csv', row.names = FALSE)

It is that call to data.frame() that is forcing legal names
on you, *not* the call to write.csv().

     cheers,

         Rolf Turner



More information about the R-help mailing list