![]() |
VOOZH | about |
rowSums() function in R Programming Language is used to compute the sum of rows of a matrix or an array. It simplifies the process of calculating the sum for each row, especially when dealing with large datasets, and can be applied to both numeric and logical data types.
rowSums(x, na.rm = FALSE, dims = 1)
Parameters:
We will create one simple matrix and with the help of rowsum function, we will calculate the sums of the rows of the matrix.
Output:
We are creating a 3D array with numbers 1 to 8. Then, we are using rowSums() with dims = 1 to sum all the values in each row across all columns and depths.
Output:
We are creating a data frame data with three columns: ID, Val1, and Val2. We then calculate the row sums of the Val1 and Val2 columns using rowSums(), which adds the values of these columns for each row. Finally, we print the calculated row sums.
Output:
We are creating a data frame data with missing values (NA) in the Val1 and Val2 columns. The rowSums() function is used to calculate the sum of the rows, and the na.rm = TRUE argument is included to ignore missing values (NA) during the summation.
Output:
We are creating a data frame data with multiple columns and missing values (NA) in Val1, Val2, val3, and val4. The rowSums() function is used to calculate the sum of Val2 and val4 for each row, while the na.rm = TRUE argument ensures that missing values (NA) are ignored during the summation.
Output:
In this article, we explored how to compute row sums in R and also demonstrated how to calculate the sums for specific columns using the rowSums() function, with options to exclude NA values.