Home Â» How to Calculate Conditional Mean in R (With Examples)

# How to Calculate Conditional Mean in R (With Examples)

You can use the following syntax to calculate a conditional mean in R:

```mean(df[df\$team == 'A', 'points'])
```

This calculates the mean of the â€˜pointsâ€™ column for every row in the data frame where the â€˜teamâ€™ column is equal to â€˜A.â€™

The following examples show how to use this syntax in practice with the following data frame:

```#create data frame
df frame(team=c('A', 'A', 'A', 'B', 'B', 'B'),
points=c(99, 90, 93, 86, 88, 82),
assists=c(33, 28, 31, 39, 34, 30))

#view data frame
df

team points assists
1    A     99      33
2    A     90      28
3    A     93      31
4    B     86      39
5    B     88      34
6    B     82      30
```

## Example 1: Calculate Conditional Mean for Categorical Variable

The following code shows how to calculate the mean of the â€˜pointsâ€™ column for only the rows in the data frame where the â€˜teamâ€™ column has a value of â€˜A.â€™

```#calculate mean of 'points' column for rows where team equals 'A'
mean(df[df\$team == 'A', 'points'])

[1] 94
```

The mean value in the â€˜pointsâ€™ column for the rows where â€˜teamâ€™ is equal to â€˜Aâ€™ is 94.

We can manually verify this by calculating the average of the points values for only the rows where â€˜teamâ€™ is equal to â€˜Aâ€™:

• Average of Points: (99 + 90 + 93) / 3 = 94

## Example 2: Calculate Conditional Mean for Numeric Variable

The following code shows how to calculate the mean of the â€˜assistsâ€™ column for only the rows in the data frame where the â€˜pointsâ€™ column has a value greater than or equal to 90.

```#calculate mean of 'assists' column for rows where 'points' >= 90
mean(df[df\$points >= 90, 'assists'])

[1] 30.66667
```

The mean value in the â€˜assistsâ€™ column for the rows where â€˜pointsâ€™ is greater than or equal to 90 is 30.66667.

We can manually verify this by calculating the average of the assists values for only the rows where points is greater than or equal to 90:

• Average of Assists: (33 + 28 + 31) / 3 = 30.66667