0
0
R Programmingprogramming~5 mins

Useful vector functions (length, sum, mean) in R Programming

Choose your learning style9 modes available
Introduction

These functions help you quickly find how many items are in a list, add them up, or find their average. They make working with numbers easier.

You want to count how many numbers are in a list.
You need to add all numbers together to get a total.
You want to find the average value of a group of numbers.
You are analyzing data and need quick summaries.
You want to check if a list is empty or not.
Syntax
R Programming
length(x)
sum(x)
mean(x)

x is a vector (a list of values).

length() counts items, sum() adds them, and mean() finds the average.

Examples
Counts how many numbers are in the list (4).
R Programming
length(c(1, 2, 3, 4))
Adds all numbers together (10).
R Programming
sum(c(1, 2, 3, 4))
Calculates the average (2.5).
R Programming
mean(c(1, 2, 3, 4))
Counts items in an empty list (0).
R Programming
length(c())
Sample Program

This program creates a list of numbers, then finds how many numbers there are, their total, and their average. It prints each result.

R Programming
numbers <- c(5, 10, 15, 20)
count <- length(numbers)
total <- sum(numbers)
average <- mean(numbers)

print(paste("Count:", count))
print(paste("Sum:", total))
print(paste("Mean:", average))
OutputSuccess
Important Notes

If the vector has no numbers, mean() returns NaN (not a number).

You can use these functions on any numeric vector, even with decimals.

By default, sum() and mean() return NA if the vector contains NA values. Use na.rm = TRUE to ignore them. length() always counts NA values.

Summary

length() tells you how many items are in a vector.

sum() adds all the numbers in the vector.

mean() finds the average value of the numbers.