0

trying to use lapply or sapply on a given mattrix using function rowSums.

Given mattrix;

mat <- matrix(1:9, ncol = 3, nrow = 3)

when I use lapply(mat, rowSums), it should calculate sum of all rows.

However its showing error

Error in FUN(X[[i]], ...) : 'x' must be an array of at least two dimensions Calls: sapply -> lapply -> FUN Execution halted

Where am I doing wrong, Please help.

Amit Peer
  • 17
  • 7

1 Answers1

1

With a matrix you can use apply:

apply(mat, 1, sum)

Parameter 1 indicates that you are performing the sum function on the rows (2 for the columns)

Leonardo
  • 2,439
  • 33
  • 17
  • 31
  • thanks, but does it mean that lapply and sapply functions cannot use matix or dataframe as input? – Amit Peer Feb 04 '21 at 11:02
  • 1
    `lapply` and `sapply` take either a vector or a list as input, but not a matrix or dataframe. You can use a dataframe inside the function to be executed, but not as an input; for example, suppose to have a dataframe `df` with 5 column `lapply (1:5, function (x) df[[i])` – Leonardo Feb 04 '21 at 11:07
  • thanks, can you please tell me how apply family functions are helpful than loops. I am not able to understand this thing.. – Amit Peer Feb 04 '21 at 12:33
  • 1
    Unfortunately the question you ask does not have an answer of a few lines. I advise you to practice slowly, trying from time to time a problem to which to apply the functions of the `apply` family. To practice, first use `for` loops and then try to replace them with functions from the `apply` (or `tidyverse`) family. I leave you an excellent starting point: https://stackoverflow.com/questions/3505701/grouping-functions-tapply-by-aggregate-and-the-apply-family – Leonardo Feb 04 '21 at 13:04