Quantcast
Channel: Active questions tagged row - Stack Overflow
Viewing all articles
Browse latest Browse all 448

apply() vs. sweep() in R

$
0
0

I was writing up notes to compare apply() and sweep() and discovered the following strange differences. In order the generate the same result, sweep() needs MARGIN = 1 while apply wants MARGIN = 2. Also the argument specifying the matrix is uppercase X in apply() but lowercase in sweep().

my.matrix <- matrix(seq(1,9,1), nrow=3)row.sums <- rowSums(my.matrix)apply.matrix <- apply(X = my.matrix, MARGIN = 2, FUN = function (x) x/row.sums)sweep.matrix <- sweep(x = my.matrix, MARGIN = 1, STATS = rowSums(my.matrix), FUN="/")apply.matrix - sweep.matrix ##yup same matrix

Isn't sweep() an "apply-type" function? Is this just another R quirk or have I lost my mind?


Viewing all articles
Browse latest Browse all 448

Trending Articles