0

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!

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
JJC
  • 3
  • 1
  • Welcome to Stack Overflow. We cannot read data into R from images. Please [make this question reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) by including a small representative dataset in a plain text format - for example the output from `dput(htrisk)`, if that is not too large. Also: (1) it may be easier to calculate the percentages before `pivot_wider` and (2) you do not define `pivot_test` in your code example. – neilfws Aug 02 '22 at 00:52

1 Answers1

0

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.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294