Reputation: 41
I'm using R to pull data from Adobe Analytics. The dataframe has column names and I am looking to add the following lines above the column names and save the file as a txt with the previous date: filename_yyyy-mm-dd.
I'm having issues adding the following above the column names:
These are the column names: Date Product Event 102 Event 103 Event 104 transactionID
Here is the final file should look like:
Upvotes: 1
Views: 993
Reputation: 1068
Here is one way to do it (assuming your dataframe is named your_data
):
line1 = '# Product Cost template file (user: 400024375 ds_id: 2)'
line2 = '# Products COGS (e102) Original Price (e103) Sale Price (e104) Purchase ID'
column_names = c( paste( line1, line2, 'Date', sep = '\n'), 'Product', 'Event 102', 'Event 103', 'Event 104', 'transactionID')
output = rbind( column_names, your_data)
write.table( output, "filename_yyyy-mm-dd.txt", sep="\t", quote = F, row.names = F, col.names = F )
Note that this assumes you do not yet have the column names in the data, which you seem to imply. If you do have the column names already in the first row, you just write output[1, 1] = paste( line1, line2, output[1, 1], sep = '\n')
instead of the rbind
line.
Alternatively, you can first write the first lines and then append the table:
line1 = '# Product Cost template file (user: 400024375 ds_id: 2)'
line2 = '# Products COGS (e102) Original Price (e103) Sale Price (e104) Purchase ID'
column_names = c( 'Date', 'Product', 'Event 102', 'Event 103', 'Event 104', 'transactionID')
names(your_data) = column_names
file_name = "filename_yyyy-mm-dd.txt"
cat( line1, line2, file = file_name, sep="\n")
write.table( your_data, file_name, sep="\t", quote = F, row.names = F, col.names = T, append = T )
(Again, if you already have the column names, just remove the column_names
parts.)
Upvotes: 1