Exchange numbers if one is more common than the other in a matrix R -
i have matrix looks like
0 0 0 0 1 2 na 0 0 0 0 0 0 0 2 1 2 0 1 0 2 say want recode rows 2 more frequent 0, replace them each other. row has 2's replaced 0 , vice versa. what's quick , easy way this?
i end this: (changing third row)
0 0 0 0 1 2 na 0 0 0 0 0 0 0 0 1 0 2 1 2 0
cheap:
t(apply(m, 1, function(x) { x2 <- x==2 x0 <- x==0 if(sum(x2)>sum(x0)) { x[x2] <- 0 x[x0] <- 2 } x }))
Comments
Post a Comment