Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add percent column to every other column in dataframe in R

I have adataframe of counts and I want to add % column after each count column.

df <- data.frame(name= c("Ji", "Ka", "Na", "Po"),
                 `a(N)`= c(1,4,5,2),
                 `b(N)`=c(0.5,04,0.8,0.3),
                 `c(N)`= c(41,49,48,42))

df
  name a.N. b.N. c.N.
1   Ji    1  0.5   41
2   Ka    4  4.0   49
3   Na    5  0.8   48
4   Po    2  0.3   42

so I want something like

df <- df %>%
  add_column(`a(%)` = df$a.N./sum(df$a.N.), .after= "a.N.") %>%
  add_column(`b(%)` = df$b.N./sum(df$b.N.), .after= "b.N.") %>%
  add_column(`c(%)` = df$c.N./sum(df$c.N.), .after= "c.N.")

  name a.N.       a(%) b.N.       b(%) c.N.      c(%)
1   Ji    1 0.08333333  0.5 0.08928571   41 0.2277778
2   Ka    4 0.33333333  4.0 0.71428571   49 0.2722222
3   Na    5 0.41666667  0.8 0.14285714   48 0.2666667
4   Po    2 0.16666667  0.3 0.05357143   42 0.2333333

My actual dataframe has many more columns so it does not make sense to apply add_column one by one. is there a way to get the percent columns with fewer lines of codes?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We may use across

library(dplyr)
library(stringr)
df %>% 
   mutate(across(-name, ~ .x/sum(.x),
    .names = "{str_remove(.col, fixed('.N.'))}(%)"))  %>%
   select(name, gtools::mixedsort(names(.)[-1]))

-output

   name a.N.       a(%) b.N.       b(%) c.N.      c(%)
1   Ji    1 0.08333333  0.5 0.08928571   41 0.2277778
2   Ka    4 0.33333333  4.0 0.71428571   49 0.2722222
3   Na    5 0.41666667  0.8 0.14285714   48 0.2666667
4   Po    2 0.16666667  0.3 0.05357143   42 0.2333333
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading