Stataq
Stataq

Reputation: 2307

how to add percentage in part of table

I have table that looks like this:

enter image description here

it can be build using codes:

overall<-structure(list(e = structure(c(a = 1L, b = 4L, c = 3L, d = 2L
), .Label = c("", "14", "194", "208"), class = "factor"), f = structure(c(a = 1L, 
b = 4L, c = 3L, d = 2L), .Label = c("", "6", "62", "68"), class = "factor"), 
    g = structure(c(a = 1L, b = 1L, c = 1L, d = 2L), .Label = c("19", 
    "7"), class = "factor"), h = structure(c(a = 2L, b = 1L, 
    c = 4L, d = 3L), .Label = c("10", "19", "3", "9"), class = "factor")), class = "data.frame", row.names = c("a", 
"b", "c", "d"))

now i want to add % by using c/b; d/b; How can I do it? As this is table, i will need to change the type so it can be calculated.

Any suggest on how to do it? Thanks.

The output that I want is sth like this, maybe also add() around percentage:

enter image description here

Upvotes: 1

Views: 84

Answers (1)

akrun
akrun

Reputation: 887941

We could convert the types from factor to numeric then loop over the columns, divide by the lag values and convert to percent_format and paste/str_c with the original column values

library(dplyr)
library(stringr)
type.convert(overall, as.is = TRUE) %>% 
     mutate(across(everything(), ~ {
     tmp <- scales::percent_format()(./lag(.))
    case_when(!is.na(tmp) ~ str_c(., ' ', tmp), TRUE ~ as.character(.))}))

-output

#       e      f       g      h
#a    <NA>   <NA>      19     19
#b     208     68 19 100% 10 53%
#c 194 93% 62 91% 19 100%  9 90%
#d   14 7%  6 10%   7 37%  3 33%

Upvotes: 2

Related Questions