row - apply() vs. sweep() in R -
i writing notes compare apply() , sweep() , discovered following strange differences. in order generate same result, sweep() needs margin = 1 while apply wants margin = 2. argument specifying matrix uppercase x in apply() 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() "apply-type" function? r quirk or have lost mind?
note apply
,
if each call ‘fun’ returns vector of length ‘n’, ‘apply’ returns array of dimension ‘c(n, dim(x)[margin])’ if ‘n > 1’
in example, margin
can (and should) set 1
in both cases; returned value apply
should transposed. easiest see if original matrix not square:
my.matrix <- matrix(seq(1,12,1), nrow=4) apply.matrix <- t(apply(x = my.matrix, margin = 1, fun = function(x) x/sum(x))) sweep.matrix <- sweep(x = my.matrix, margin = 1, stats = rowsums(my.matrix), fun="/") all.equal(apply.matrix, sweep.matrix) # [1] true
also see answer can implement 'sweep' using apply in r?, says same thing.
Comments
Post a Comment