I have seen this question being asked multiple times on the R mailing list, but still could not find a satisfactory answer.
Suppose I a matrix m
m <- matrix(rnorm(10000000), ncol=10)
I can get the mean of each row by:
system.time(rowMeans(m)) user system elapsed 0.100 0.000 0.097
But obtaining the minimum value of each row by
system.time(apply(m,1,min)) user system elapsed 16.157 0.400 17.029
takes more than 100 times as long, is there a way to speed this up?
First of all, create a data frame. Then, using plus sign (+) to add two rows and store the addition in one of the rows. After that, remove the row that is not required by subsetting with single square brackets.
Calculating the sum of rows of the array in R To calculate the sum of rows of an array in R, use the rowSums() function. Let's create an array and use the rowSums() function to calculate the sum of rows of the array. To create an array in R, use the array() function.
The rowMeans() function in R can be used to calculate the mean of several rows of a matrix or data frame in R.
The rowMeans() is a built-in R function that calculates the mean of each row of a matrix or array. The rowMeans() method returns the mean for the specified rows for the data frame, matrix, or arrays. The rowMeans() function is very useful when you want to find the mean values rows.
You could use pmin
, but you would have to get each column of your matrix into a separate vector. One way to do that is to convert it to a data.frame then call pmin
via do.call
(since data.frames are lists).
system.time(do.call(pmin, as.data.frame(m))) # user system elapsed # 0.940 0.000 0.949 system.time(apply(m,1,min)) # user system elapsed # 16.84 0.00 16.95
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With