To divide the values in a table based on a side column in R, you can use the dplyr
and tidyr
packages. Here is an example code that demonstrates how to accomplish this task:
main.r584 chars21 lines
The output will be a dataframe with the total value for each category, and the percentage of each category out of the total:
main.r120 chars5 lines
In this example, we first grouped the data by category using the group_by
function from dplyr
. We then calculated the sum of the values in each category using the summarise
function.
Next, we used the pivot_wider
function from tidyr
to spread the data into wide format, which separates the categories into their own columns. We then calculated the percentage of each category out of the total by dividing the value by the sum of values of both categories and multiplying by 100. Lastly, we used the round
function to round the percentages to 2 decimal places.
gistlibby LogSnag