I want to calculate percent of each column in a Dataframe and make a custom name for each one.
Consider following code:
a<-structure(list(year = 2000:2005, Col1 = 1:6, Col2 = c(1L, 4L,
9L, 16L, 25L, 36L)), row.names = c(NA, -6L), class = "data.frame")
> a
year Col1 Col2
1 2000 1 1
2 2001 2 4
3 2002 3 9
4 2003 4 16
5 2004 5 25
6 2005 6 36
a<-a %>% rowwise() %>%
mutate(total = sum(across(starts_with("Col")), na.rm = T)) %>% data.frame()
a %>%
mutate_at(vars(starts_with("Col")) , funs(P = ./a$total * 100))
The output is as follows:
How to handle the name of last two columns(for example per_Col1 and per_Col2 instead Col1_P and Col2_P, main question) ? Is there a better way(using dplyr package) to do this?( instead of calculate sum of columns and then divide each one to it)
