Conditional Mean in R with examples

Conditional Mean in R, to calculate a conditional mean in R, use the following syntax.

mean(data[data$Name == 'India', 'points'])

For every row in the data frame where the ‘Name’ column equals ‘India,’ this calculates the mean of the ‘points’ column.

With the following data frame, the following examples demonstrate how to use this syntax in practice.

Let’s create a data frame

data <- data.frame(Name=c('India', 'India', 'England', 'England', 'India', 'India'),
                 Score=c(360, 290, 293, 286, 288, 182),
                 points=c(8, 6, 7, 6, 7, 4))

Now we can view the data frame

data
     Name Score points
1   India   360      8
2   India   290      6
3 England   293      7
4 England   286      6
5   India   288      7
6   India   182      4

Example 1: Calculate Conditional Mean for Categorical Variable

For every row in the data frame where the ‘Name’ column equals ‘India’ this calculates the mean of the ‘points’ column.

With the following data frame, the following examples demonstrate how to use this syntax in practice.

Animated Graph GIF with gganimate & ggplot » finnstats

mean(data[data$Name == 'India', 'points'])
1] 6.25

The mean value in the ‘points’ column for the rows where ‘Name’ India is 6.25.

In the same way, you can calculate the ‘points’ score of the other ‘Name’.

Example 2: Calculate Conditional Mean for Numeric Variable

The code below shows how to compute the mean of the ‘score’ column for only the rows in the data frame where the ‘points’ column is higher than or equal to 7.

Let’s calculate the mean of the ‘score’ column for rows where ‘points’ >= 7

mean(data[data$points >= 7, 'Score'])
[1] 313.6667

The mean value in the ‘score’ column for the rows where ‘points’ is greater than or equal to 7 is 313.6667.

mean(data[data$points >= 5, 'Score'])
[1] 303.4

The mean value in the ‘score’ column for the rows where ‘points’ is greater than or equal to 5 is 303.4

How to Perform Tukey HSD Test in R » Quick Guide » finnstats

You may also like...

Leave a Reply

Your email address will not be published.