Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a line of metadata above a dataframe

Tags:

dataframe

r

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?

like image 810
Gabriel G. Avatar asked Jan 19 '26 02:01

Gabriel G.


1 Answers

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.

like image 51
slava-kohut Avatar answered Jan 20 '26 17:01

slava-kohut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!