divide value in a tabble based on side column in r

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.r
library(dplyr)
library(tidyr)

# create sample data
df <- data.frame(category = c("A", "A", "B", "B"), 
                 value = c(10, 20, 30, 40))

# group data by category and calculate the sum of values
df_sum <- df %>%
  group_by(category) %>%
  summarise(total_value = sum(value))

# spread the data into wide format and calculate the percentage
df_percent <- df_sum %>%
  pivot_wider(names_from = category, values_from = total_value) %>%
  mutate(A_percent = round(A / sum(c(A, B)) * 100, 2),
         B_percent = round(B / sum(c(A, B)) * 100, 2))

# view the result
df_percent
584 chars
21 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.r
# A tibble: 1 x 3
      A     B A_percent B_percent
  <dbl> <dbl>     <dbl>     <dbl>
1    30    70      30        70  
120 chars
5 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