rjanitor

R: Replace last column of the last row with "-" in a dataframe


I am creating rowsum of the table like below. I want to remove the rowsum of the last column of the table.

mytable
A B C
a1 22 33
b1 12 10
Total 34 43

My code to generate rowsums

library(dplyr)
library(formattable)
    mytable <- mytable %>%
      arrange(rowSums(is.na(.))) %>%
      adorn_totals("row") %>%
      formattable()

I want to replace last column of the row Total (in this case value 43) with "-". i tried

last_row <- tail(mytable, n=1)
last(last_row) <- "-"

Solution

  • mytable[nrow(mytable),ncol(mytable)] <- "-"
    mytable
    #       A  B  C
    # 1    a1 22 33
    # 2    b1 12 10
    # 3 Total 34  -
    

    Note that with this, your C column is no longer a number:

    'data.frame':   3 obs. of  3 variables:
     $ A: chr  "a1" "b1" "Total"
     $ B: int  22 12 34
     $ C: chr  "33" "10" "-"
    

    Data

    mytable <- structure(list(A = c("a1", "b1", "Total"), B = c(22L, 12L, 34L), C = c(33L, 10L, 43L)), class = "data.frame", row.names = c(NA, -3L))