simulation - R: strange result using sample function in apply -
i running simulation takes sample of values in matrix starts 1 column. put them through selection criteria , each row in matrix randomly selects value output , saves random selection. reason when apply sample() matrix on rows have real number , na, returns number not available sampled. may doing wrong sample() function, don't understand unknown value coming from.
example code:
theta <- c(30, 84, 159, 32, 60, 97) omega <- 0.01 k <- 1 xn <- matrix(c(30, 84, 159, 32, 60, 97), ncol=1) dup <- xn * 2 set.seed(1) z <- matrix(rbinom(n=rep(1,length(dup)),size = as.vector(dup),prob = 0.5),nrow = nrow(dup)) z1 <- dup - z xn <- cbind(z, z1) # put both in matrix w <- exp( -(1/2)*( ( ( xn - theta ) / theta ) ^2 / omega ) ) set.seed(1) z <- matrix(rbinom(nrow(w) * ncol(w), 1, w), nrow=nrow(w), ncol=ncol(w) ) xn <- ifelse ( z == 0, 0, xn ) xn [,1] [,2] [1,] 32 0 [2,] 78 0 [3,] 144 0 [4,] 0 30 [5,] 60 60 [6,] 92 102
i don't want include 0 values change them na , apply sample() function each row return single value.
xn[which(xn==0)] <- na set.seed(1) xn2 <- matrix(apply(xn, 1, function(x){sample(x[!is.na(x)], size = k)}), ncol = k)
what should is
xn [,1] [1,] 32 [2,] 78 [3,] 144 [4,] 30 [5,] 60 [6,] 102
but is:
xn [,1] [1,] 9 [2,] 30 [3,] 83 [4,] 24 [5,] 60 [6,] 102
specifically, in example, values 9, 23, 55, , 24 coming out of know of.
does know mistake making when take sample?
to summarize comments,
?sample
says
if x has length 1, numeric (in sense of is.numeric) , x >= 1, sampling via sample takes place 1:x.
for application, when x
of length 1, want use value of x
instead of sample(x)
. can adapt code adding check see if length of x
greater 1 before passing through sample
matrix(apply(xn, 1, function(x){ if (length(x[!is.na(x)]) > 1) { sample(x[!is.na(x)], size = k) } else x[!is.na(x)] }), ncol=k) [,1] [1,] 32 [2,] 78 [3,] 144 [4,] 30 [5,] 60 [6,] 102
Comments
Post a Comment