Reputation: 822
My question is probably very simple, but I can't find an answer
I have the dataframe (where the first row are in fact colnames)
a b c d e
1
2
3
4
5
And I need to include some metadata:
>this is metadata
a b c d e
1
2
3
4
5
How can I do that?
Upvotes: 3
Views: 844
Reputation: 11
Easiest way is to use openxlsx.
https://cran.r-project.org/web/packages/openxlsx/vignettes/Introduction.html
as in:
header <- "this is metadata"
df <- my dataframe
wb <- createWorkbook()
#create an empty workbook
addWorksheet(wb, sheetName = "df_name", gridLines = F)
#add one or more worksheets specifying the name you want for the worksheet
writeData(wb, 1, x = header, startCol = 1, startRow = 1)
#write your header to the workbook
writeDataTable(wb, sheet = 1, df, startCol = 1, startRow = 2)#)
#write your data to the workbook
saveWorkbook(wb, "df_name.xlsx", overwrite = TRUE)
#export your workbook to excel file
#not run for this example
Upvotes: 1
Reputation: 4233
There are two things you could do if you want to retain some metadata:
1) If you want to manipulate data frames with metadata in your R session, you can create a new S3 class that inherits from data.frame
and add a metadata
attribute to it. You can find some relevant information here
2) If you want to save a data frame with metadata to disk, you can add a comment line at the top of your csv file (or any other format that you prefer). Something like this will work:
con <- file(paste0(base_path, file_name),'wt')
cat(paste0(comment_string,'\n'), file = con)
write.table(your_data_frame,
con,
append = TRUE,
sep = ',',
dec = '.',
row.names = FALSE,
col.names = FALSE)
close(con)
where comment_string
is your metadata and your_data_frame
is your data frame.
Upvotes: 4