To calculate percentage by group in R, you can use group_by() and mutate() function from dplyr package.

The following method shows how you can do it with syntax.

Method: Use dplyr Package

library(dplyr)

dataframe %>%
  group_by(column1) %>%
  mutate(percent = column2/sum(column2))

The following example shows how to calculate percentage by group in R.

Use dplyr Package to Calculate Percentage by Group

Let’s see how we can calculate percentage by group in R:

# Import library
library(dplyr)

# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","A","B","C","D"),
                 Pressure=c(78.2, 78.2, 71.7, 80.21, 80.21, 82.56, 72.12, 73.85),
                 Temperature=c(35, 36, 36, 38, 32, 32, 31, 34))

# Calculate percentage of Pressure group by Machine_name
p <- df %>%
  group_by(Machine_name) %>%
  mutate(percent = Pressure/sum(Pressure))

# Print percentage
print(p)

Output:

 Machine_name Pressure Temperature percent
  <chr>           <dbl>       <dbl>   <dbl>
1 A                78.2          35   0.494
2 B                78.2          36   0.486
3 C                71.7          36   0.499
4 D                80.2          38   0.521
5 A                80.2          32   0.506
6 B                82.6          32   0.514
7 C                72.1          31   0.501
8 D                73.8          34   0.479

As the output shows percentage of Pressure column which group by Machine_name column of data frame.