To add count column to data frame in R, you can use add_count() function from dplyr package.
The following method shows how you can do it with syntax.
Method 1: Use add_count() Function
library(dplyr)
df %>%
add_count(column1, column2, name = "count")
The following example shows how to add count column to dataframe in R.
Using add_count() Function
Let’s see how we can add count column to dataframe using add_count() function:
library(dplyr)
# Create dataframe
df <- data.frame(Machine_name=c("A","B","C","D","E","F","G","H","A","B","A","C","D","B","E","H"),
Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58,9.6,8.85,7.89,10.24,12.36,11.45,9.47,8.12))
# Add count column
df <- df %>%
add_count(Machine_name, name = "count")
# Print dataframe
print(df)
Output:
Machine_name Pressure count
1 A 12.39 3
2 B 11.25 3
3 C 12.15 2
4 D 13.48 2
5 E 13.78 2
6 F 12.89 1
7 G 12.21 1
8 H 12.58 2
9 A 9.60 3
10 B 8.85 3
11 A 7.89 3
12 C 10.24 2
13 D 12.36 2
14 B 11.45 3
15 E 9.47 2
16 H 8.12 2
Here the output shows new coolumn added to dataframe which having count of repeated elements in Machine_name column of dataframe.