I am trying to fill a matrix with specific values based on a different matrix.
I created an empty matrix with:
n <- 64 #length of matrix
vector_walk<- matrix(0, ncol = 1, nrow = n)
Then I filled that matrix from this Distribution
n <- 100000 #How many observations in the distribution
mu <- 180 #Mean vector for distribution
kappa <- 1.5 #How wide the distribution is
mu <- circular(mu, units = c("degrees"),
modulo = c("2pi"),
template = ("geographics"))
Dist <- rvonmises(n, mu, kappa, control.circular=list(units="degrees"))
Filling the matrix
for (i in 1:n){
vector[i] = sample(Dist, 1)
}
Now here is where I am stuck. I want to fill a new matrix "grid_walk" with 2 columns and conditionally fill it with values based on the "vector_walk" matrix. I want to put a 0 in the first column and a 1 in the second whenever the "vector matrix has a value greater than 0 and less than 23 and a few others listed below. I am trying this for loop with if statements
for (j in 1:2){
for(i in 1:n){
if(vector_walk[i] > 0 & vector_walk[i] < 23) grid_walk[i,j] <- c(0,1)
if(vector_walk[i] > 23 & vector_walk[i] < 68) grid_walk[i,j] <- c(1,1)
if(vector_walk[i] > 68 & vector_walk[i] < 113) grid_walk[i,j] <- c(1,0)
if(vector_walk[i] > 113 & vector_walk[i] < 158) grid_walk[i,j] <- c(1,-1)
if(vector_walk[i] > 158 & vector_walk[i] < 203) grid_walk[i,j] <- c(0,-1)
if(vector_walk[i] > 203 & vector_walk[i] < 248) grid_walk[i,j] <- c(-1,-1)
if(vector_walk[i] > 248 & vector_walk[i] < 293) grid_walk[i,j] <- c(-1,0)
if(vector_walk[i] > 293 & vector_walk[i] < 338) grid_walk[i,j] <- c(-1,1)
if(vector_walk[i] > 338 & vector_walk[i] < 361) grid_walk[i,j] <- c(0,1)
}
}
Any help would be appreciated as I have never used if or for statements in R
question from:
https://stackoverflow.com/questions/65893463/conditionally-fill-matrix-based-on-values-of-another-matrix-using-for-loop 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…