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

199 Views Asked by At

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) <- "-"
3

There are 3 best solutions below

0
r2evans On BEST ANSWER
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))
0
TarJae On

We could use adorn_totals for specific columns like this, see here https://github.com/sfirke/janitor/issues/219:

library(formattable)
library(janitor)
library(dplyr)

mytable <- data.frame(A = c("a1", "b1"), B = c(22, 12), C = c(33, 10))

mytable %>%
  arrange(rowSums(is.na(.))) %>%
  adorn_totals(,,,,"B") %>%
  formattable()

enter image description here

2
LMc On

Here is an option using last_col and last row_number (credit @r2evans) from dplyr to identify the cell and make the substitution. This is easily implemented in a pipe chain:

mytable %>% 
  mutate(across(last_col(), ~ ifelse(row_number() == n(), "-", .)))

As mentioned by others, I would also like to highlight that C is now character so numeric operations will likely not work on the column.

If for some reason your "Total" row was not the last row, you can simply adjust the ifelse condition to be A == "Total".

Output

      A  B  C
1    a1 22 33
2    b1 12 10
3 Total 34  -