R Mean and Median

We can easily find the mean and median values from a vector or set or dataframe using the mean() and median() functions respectively. Let us learn about them with examples:

R mean

To get the mean of the values in the R programming language, use the mean() method. Let us see an example to calculate the mean:

# A Vector 
# Marks of a student in various subjects
marks <- c(95, 99, 90, 85, 87)

# Find Mean i.e. the average marks using the mean()
res <- mean(marks)
res

Output

[1] 91.2

We can also trim the left and right observations using the trim parameter of the mean() method in R. The vector will be first sorted, then according to the value in the parameter, the values will get trimmed, for example trim = 0.2 would mean trim two values from the left as well right.

Here is an example:

# A Vector 
# Marks of a student in various subjects
marks <- c(95, 99, 90, 85, 87, 79, 91, 65, 82, 80)

# Find Mean i.e. the average marks using the mean()
# The trim parameter will sort and then trims the observations
res <- mean(marks, trim = 0.2)
res

Output

[1] 85.83333

The vector will be sorted first above:

65, 79, 80, 82, 85, 87, 90, 91, 95, 99

Then, 0.2 means two observations from both the left position will get removed and then the mean gets calculated for the rest of the observations.

R median

To get the median of the values in the R programming language, use the median() method. Median is defined as the middle value of the given list. Let us see an example to calculate the median:

# A Vector 
# Marks of a student in various subjects
marks <- c(95, 99, 90, 85, 87)

# Find Median i.e. the middle value
res <- median(marks)
res

Output

[1] 90

We can also see another example, wherein we can drop the missing values using the na.rm parameter. Let us see an example and first create a vector with NA values:

# A Vector with missing values
# Marks of a student in various subjects
marks <- c(95, 99, 90, 85, 87, NA, 92, NA)

# Find Median i.e. the middle value
# We have set the na.rm parameter to TRUE to remove the missing values
res <- median(marks, na.rm = TRUE)
res

Output

[1] 91

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

R String Operations
R Min and Max
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment