Compute the Sum of Rows of a Matrix or Array in R Programming – rowSums Function
rowSums Function in R rowSums() function in R Programming Language is used to compute the sum of rows of a matrix or an array.
Syntax:
rowSums(x, na.rm = FALSE, dims = 1)
Parameters:
x: array or matrix
dims: Integer: Dimensions are regarded as ârowsâ to sum over. It is over dimensions dims+1,…
Compute the Sum of Rows of a Matrix in R Programming We will create one simple matrix and with the help of rowsum function, we will calculate the sums of the rows of the matrix.
R
x <- matrix(rep(2:10), 3, 3)
print(x)
rowSums(x)
Output:
[, 1] [, 2] [, 3]
[1, ] 2 5 8
[2, ] 3 6 9
[3, ] 4 7 10
[1] 15 18 21
Compute the Sum of Rows of a Array in R Programming We will create one simple array and with the help of rowsum function, we will calculate the sums of the rows of the array.
R
x <- array(1:8, c(2, 2, 2))
print(x)
rowSums(x, dims = 1)
Output:
,, 1
[, 1] [, 2]
[1, ] 1 3
[2, ] 2 4,, 2
[, 1] [, 2]
[1, ] 5 7
[2, ] 6 8
[1] 16 20 Compute the Sum of Rows of a data frame in R Programming We will create one simple data frame and with the help of rowsum function, we will calculate the sums of the rows of the dataframe.
R
data <- data.frame(
ID = c(1, 2, 3),
Val1 = c(10, 20, 30),
Val2 = c(5, 15, 25)
)
print(data)
row_sums <- rowSums(data[, c("Val1", "Val2")])
print(row_sums)
Output:
ID Val1 Val2 1 1 10 5 2 2 20 15 3 3 30 25 [1] 15 35 55 Use rowSums() with NA Values in Data Frame Now we create one dataset with missing values and then we use rowsums function to calculate sum of rows of missing values.
R
data <- data.frame(
ID = c(1, 2, 3),
Val1 = c(10, NA, 30),
Val2 = c(5, 15, NA)
)
print("Original Data Frame with Missing Values:")
print(data)
row_sums <- rowSums(data[, c("Val1", "Val2")], na.rm = TRUE)
row_sums
Output:
ID Val1 Val2 1 1 10 5 2 2 NA 15 3 3 30 NA [1] 15 15 30 We use na.rm = TRUE argument in rowSums() is used to treat missing values as zero during the sum calculation.
Use rowSums() with Specific Rows Now we can create one dataframe and select few specific rows for calculate the sum of the rows using rowSums function.
R
data <- data.frame(
ID = c(1, 2, 3),
Val1 = c(10, NA, 30),
Val2 = c(5, 15, NA),
val3 = c(NA, 20, 5),
val4 = c(15, 25, NA)
)
print("Original Data Frame with Missing Values:")
print(data)
row_sums <- rowSums(data[, c("Val2", "val4")], na.rm = TRUE)
print("Row Sums:")
print(row_sums)
Output:
ID Val1 Val2 val3 val4 1 1 10 5 NA 15 2 2 NA 15 20 25 3 3 30 NA 5 NA [1] "Row Sums:" [1] 20 40 0 Here we are select second and forth rows for the calculating sum off the specific rows.
Last Updated :
28 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...