Page 237 - Data Science class 11
P. 237
After the execution of the above code, the following result will be displayed:
6.10.4 example of calculations across array elements
You can do calculations across the elements in an array using the apply() function.
Syntax
apply(x, margin, fun)
The following is a description of the parameters used.
• x is an array.
• margin is the name of the data set used.
• fun is the function to be applied across the elements of the array.
Now you will use the apply() function below to calculate the sum of the elements in the rows of an array across all
the matrices.
Example
Enter the following code snippet:
# Creating two vectors of different lengths.
vector1 <- c(4,8,3)
vector2 <- c(11,12,13,14,15,16)
# Taking these vectors as input to the array.
new.array <- array(c(vector1,vector2),dim = c(3,3,2))
print(new.array)
# Using apply to calculate the sum of the rows across all the matrices.
result <- apply(new.array, c(1), sum)
print(result)
Programming with R 235

