1. Introduction
This R program calculates the sum, mean, and product of a given vector, while ignoring any NA (Not Available) or NaN (Not a Number) elements in the vector.
2. Program Steps
1. Create a vector that may include NA or NaN elements.
2. Calculate the sum of the vector, ignoring NA and NaN.
3. Calculate the mean of the vector, ignoring NA and NaN.
4. Calculate the product of the vector, ignoring NA and NaN.
5. Display the sum, mean, and product.
3. Code Program
# Step 1: Create a vector with possible NA or NaN elements
vector <- c(1, 2, 3, NA, NaN, 4, 5)
# Step 2: Calculate the sum, ignoring NA and NaN
sum_vector <- sum(vector, na.rm = TRUE)
# Step 3: Calculate the mean, ignoring NA and NaN
mean_vector <- mean(vector, na.rm = TRUE)
# Step 4: Calculate the product, ignoring NA and NaN
product_vector <- prod(vector, na.rm = TRUE)
# Step 5: Display the results
print("Sum of the vector:")
print(sum_vector)
print("Mean of the vector:")
print(mean_vector)
print("Product of the vector:")
print(product_vector)
Output:
Sum of the vector: [Sum of the vector excluding NA and NaN] Mean of the vector: [Mean of the vector excluding NA and NaN] Product of the vector: [Product of the vector excluding NA and NaN]
Explanation:
1. vector <- c(1, 2, 3, NA, NaN, 4, 5): Initializes the vector with numbers and potential NA or NaN values.
2. sum(vector, na.rm = TRUE): Calculates the sum of the vector while removing NA and NaN elements.
3. mean(vector, na.rm = TRUE): Calculates the mean of the vector, excluding NA and NaN elements.
4. prod(vector, na.rm = TRUE): Computes the product of the vector's elements, ignoring NA and NaN.
5. print("Sum of the vector:"): Prints a message indicating the sum.
6. print(sum_vector): Displays the sum of the vector.
7. print("Mean of the vector:"): Prints a message indicating the mean.
8. print(mean_vector): Displays the mean of the vector.
9. print("Product of the vector:"): Prints a message indicating the product.
10. print(product_vector): Displays the product of the vector.
Comments
Post a Comment