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

Time:08-02

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.

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!

CodePudding user response:

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.

  • Related