-1

I have developed the following code to create a table in r and export it to csv where I format it to insert into a word document. This example contains the total of each fruit and the month in which they were sold.

library (lubridate)
Table<-read.csv("Fruit.csv")

#Creates a month name column
Table$Month<- month(Table$Date, label=TRUE)

#Creates the frequency table
FreqTable<-addmargins(table(Table$Fruit, Table$Month))

#Exports to CSV
write.csv(FreqTable,"Table.csv")

The above produces a table that looks like:

Example of table

I have 3 main questions about the table and Im not sure if they are possible to fix.

  1. How can I add a title for the 1st column? I just want to add 'Fruit' as the column name.

  2. The data I have goes up until the end of June, how can I remove all the remaining months out of the table for where there is no data? (July - Dec)

  3. How can I change the row and column header 'sum' to 'Total'?

Any assistance would be appreciated.

  • It's not possible to tell from your example whether the first column is a column or a list of row names. `str(Table)` will tell you whether the fruit column is a column or a vector of row names. That would give you two different solutions. To change column names you use `names(object)[column] <- "New_Name"`. So `names(Table)[1] <- "Fruit"` – Adam Sampson Jul 16 '18 at 14:15
  • Welcome to stackoverflow. See [this link on how to make a great reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1) for your question. – Anonymous coward Jul 16 '18 at 21:09

1 Answers1

0

Some data already in frequency format.

fruit <- data.frame(Jan = c(4, 5, 2), Feb = c(1, 3, 0), March = c(0, 0, 0), row.names = c("Apples", "Grapes", "Oranges"))

fruit$sum <- rowSums(fruit)
fruit <- fruit[!colSums(fruit > 0) == 0] # Subset your columns with sums > 0
colnames(fruit)[3] <- "Total" # Rename column

You'd have to add a column with your fruit types to add a column name for it. Do that and just add row.names = FALSE when you write your csv.

Anonymous coward
  • 2,061
  • 1
  • 16
  • 29