0

I would like to print a table with sums, but only for certain columns. Let's say for this example only column 2 and 3, while I would like to print the entire table (with sums for only 2 columns) and maintaining the original structure of the table.

x <- data.frame(
  fruit = c("apple", "orange", "banana"),
  amount = c("10", "5", "4"),
  price = c(2.5, 2, 1.5),
  taste = c("great", "super", "nice"))
x`

Could you please help me with this?

Peter P.
  • 51
  • 7

2 Answers2

2

To help you in the right direction. Would do it this way:

x$amount <- as.numeric(x$amount)
x["Total" ,] <- colSums(x[c("amount", "price")])
print(x, na.print = "", row.names = FALSE)

Output:

   fruit amount price taste
   apple      1   2.5 great
  orange      3   2.0 super
  banana      2   1.5  nice
              6   6.0      
Fierr
  • 185
  • 2
  • 10
  • Great Fierr, this is way better than I found out. Thanks a lot. Do you also know how to use row.names = false and if possible leave out the NA's? – Peter P. May 24 '18 at 19:46
  • Would use print(x, na.print = "", row.names = FALSE) to show empty fields and to hide the rownumbers. Note: this does not change the underlying content. – Fierr May 24 '18 at 20:11
  • Yes, that's close, I think I forgot to mention, that I like the word "Total". If this can be placed in column fruit it would be totally perfect. – Peter P. May 24 '18 at 20:21
  • Its probably possible with some additional tweaking, but I wouldn't go that way if I were you. If you really need a specific format, think about putting the output in Excel for example and doing the tweaking there. – Fierr May 24 '18 at 20:30
  • I found out that the janitor package can make this work (with the word Total). https://stackoverflow.com/questions/27969616/add-column-sum-to-table/48371963 – Peter P. Jul 18 '18 at 16:41
2
Update: 

x <- data.frame(
fruit = c("apple", "orange", "banana"),
amount = c(10, 5, 4),
price = c(2.5, 2, 1.5),
taste = c("great", "super", "nice"))
x

library(janitor)
x %>%
adorn_totals("row")

How do I add a row to a data frame with totals?

Peter P.
  • 51
  • 7