[R] write.csv: set the name of the column containing the row.names

Luca Cerone luca.cerone at gmail.com
Wed Mar 19 12:05:32 CET 2014


Thanks Duncan,
I knew that, I wanted to know if there was some way not involving
having to recreate the df.
It is not a big issue in this case (they are not very big), but it
might be problematic for big data frames.

Thanks for advice on using col.names=NA.

Cheers,
Luca
Luca Cerone

Tel: +34 692 06 71 28
Skype: luca.cerone


On Wed, Mar 19, 2014 at 11:44 AM, Duncan Murdoch
<murdoch.duncan at gmail.com> wrote:
> On 14-03-19 6:12 AM, Luca Cerone wrote:
>>
>> Hi everybody,
>> I am sorry if this is a silly question (I have tried to search it at
>> http://tolstoy.newcastle.edu.au/R/ but I get a 404 page).
>>
>> I have a script writing some data.frames to csv files.
>> I write the csv files using the write.csv function and the option
>> row.names=TRUE.
>> Everything works fine, except that I am not able to set the name of
>> the column holding the row.names.
>>
>> For example I tried to set the column name to ID like this:
>>
>>      df = data.frame(a=c(1,2,3), b=c(3,4,5))
>>      rownames(df) = c("A","B","C")
>>
>>      write.csv(df, row.names=TRUE, colnames=c("ID", colnames(df)))
>>
>> This fails with the following error:
>>      Error in write.table(df, row.names = TRUE, colnames = c("ID",
>> colnames(df)),  :
>>            unused argument (colnames = c("ID", colnames(df)))
>>
>> How can I do this? I have tried to use write.table() as well, but it
>> seems I never get to set the options right.
>>
>
> You can't get a column heading for the row names.  If you want a blank entry
> there, use col.names=NA and row.names=TRUE.  If you want the heading to be
> ID, then you need to write the row names as a regular column of the
> dataframe, e.g.
>
> df2 <- data.frame(ID=rownames(df), df)
>
> and then write df2 *without* rownames (so they don't appear twice).
>
> Duncan Murdoch




More information about the R-help mailing list