Killian
Killian

Reputation: 89

Converting a vector to a matrix

Here is my code:

n <- 10
set.seed(100)
d <- rep(NA, n)
d[1] <- 0
y <- runif(n)
a <- 5

for (i in (2:(length(y)+1))) {
 d[i] <- d[i-1] + y[i-1]
}

store.x <- NULL
for(j in 1:a) {
 x <- runif(1, min = 0, max = sum(y))
  for (i in 1:(length(y))) {
   if(x <= d[i+1] && x > d[i]) {
    store.x[j] <- i
    break
  }
 }
}
store.x

Now store.x prints out 7, 9, 4, 6, 8. I want to be able to put these into a matrix where the numbers that store.x prints correspond to the columns and the row is in order of the numbers. So the first entry would be in row 1 column 7, next would be row 2 column 9 and so on. I want to start with a n by n matrix filled with zeros and then add one the row/column that these numbers are in. I'm not sure how to go about doing this. Any help would be appreciated!

Upvotes: 1

Views: 92

Answers (1)

zacdav
zacdav

Reputation: 4671

So creating a matrix mt that will be filled and then NA's changed to zeros.

n <- 10
set.seed(100)
d <- rep(NA, n)
d[1] <- 0
y <- runif(n)
a <- 220
mt = matrix(nrow = n, ncol = n)
mt[is.na(mt)] = 0
for (i in (2:(length(y)+1))) {
    d[i] <- d[i-1] + y[i-1]
}

store.x <- NULL
for(j in 1:a) {
    x <- runif(1, min = 0, max = sum(y))
    for (i in 1:(length(y))) {
        if(x <= d[i+1] && x > d[i]) {
            store.x[j] <- i

            if(length(which(i == store.x)) > 1){
                mt[which(mt[,i] != 0),i] = mt[which(mt[,i] != 0),i] + 1
            } else {
                mt[(which(rowSums(mt) == 0)[1]),i] = 1
            }

            break
        }
    }
}

what i added was this following logic

if(length(which(i == store.x)) > 1){
                    mt[which(mt[,i] != 0),i] = mt[which(mt[,i] != 0),i] + 1
                } else {
                    mt[(which(rowSums(mt) == 0)[1]),i] = 1
                }

if the number created exists in store.x more than once then we find the existing entry (column corresponds to i and row will be the one which is not 0). If the number does not exist we then find the first row which has no entry and use that.

Upvotes: 2

Related Questions