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

I am trying to make a table with percentages after having used pivot.wider in R

I am currently trying to make a table with percentages after having used the pivot.wider command on a variable. htrisk is the datafile and menopaus and invasive are variables. Using the following code:

p_t <- htrisk %>% 
  group_by(menopaus, invasive) %>%
  count(invasive, name = "n") %>%
  pivot_wider(names_from = invasive, values_from = n, values_fill = 0)
pivot_test

Current table with wanted changes

I get the table above which is what I want, but I want to add two percentage columns which show the percents for let’s say pre-meno/no and pre-meno/yes. Then for post-meno/no and post-meno/yes.

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

I have tried using the prop.table but I get the error "Error in FUN(X[[i]], …) :
only defined on a data frame with all numeric-alike variables".

Any help or direction would be much appreciated!

>Solution :

With dplyr, use mutate to add new columns.

pivot_test %>%
  mutate(
    pct_no = No / (No + Yes),
    pct_yes = 1 - pct_no
  )

If you need more help, please share enough sample data in valid R syntax to make a reproducible example, e.g. dput(pivot_test[1:3, ]) for the first 3 rows.

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