Converting a vector to a matrix - r

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!

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.

Related

Testing a prime number with loop 1: sqrt(x)

I am learning about loops and I have this code to check if a number is prime or not, but doesn't work. Where is the bug?
x <- 7
y <- seq(1,sqrt(x),by=1)
for(i in 1: sqrt(x)){
if(y[x%%y == 0]) {
print("FALSE")
}else{
print("TRUE")
}
}
This gives me the right solution, but it repeats the answer as many times as number of elements in i. Also I would like to ask how to use function inside a for with if:
i <- c(1: sqrt(x))
y3 <- x%%i == 0
y4 <- y3[-1]
for(value in i){
if(y4 == FALSE) {
print("TRUE")
}else{
print("FALSE")
}
}
version 3, gives me the solution but for evey element in i:
x <- 107
i <- c(1: sqrt(x))
y3 <- c(x%%i == 0)
y4 <- y3[-1]
for(value in i){
if(all(y4==F)) {
print("TRUE")
}else{
print("FALSE")
}
}
Since you mentioned that you must use a loop, the following code will work:
x <- 7
y <- seq(1, ceiling(sqrt(x)), by=1)
# is.factor is a vector which checks whether each element in y is a factor or not
# initialize to F
is.factor = F
# Start at y = 2 because 1 will be a factor
for(i in 2:length(y) ){
# Check whether current value in vector is a factor of x or not
# if not a factor, set value in index to F, otherwise set to T
ifelse( x%%y[i] != 0, is.factor[i] <- F, is.factor[i] <- T)
# If we are at the last element in y, print a result
if(i == length(y)){
# check if we have any factors.
# if we have any factors (i.e. any index in is.factor vector is T), then number is not prime
ifelse( any(is.factor), print("FALSE"), print("TRUE") )
}
}
You can do this-
check_prime <- function(num) {
if (num == 2) {
TRUE
} else if (any(num %% 2:(num-1) == 0)) {
FALSE
} else {
TRUE
}
}
> check_prime(7)
[1] TRUE

How to repeat same codes in 10 times and get those results in R?

Here is my code:
f.x <- function(x) {
60*x^3*(1-x)^2
}
x <- seq(0, 1, length=100)
n.samps <- 1000
n <- 0 # counter for accepted
i <- 0 # iterations
samps <- numeric(n.samps)
while (n < n.samps) {
y <- runif(1)
i <- i + 1
u <- runif(1)
if (u < f.x(y) / 2.0736) {
n <- n + 1
samps[n] <- y
}
}
I want to repeat the code above for 10 times, each time an "i" will be produced. I want to take the average of these ten "i". Instead of run the code each time, is there any way I can run one time but get 10 trials?
You can try placing your entire script into a function, and then just call it 10 times from a loop:
getValue <- function() {
x <- seq(0, 1, length=100)
n.samps <- 1000
n <- 0 # counter for accepted
i <- 0 # iterations
samps <- numeric(n.samps)
while (n < n.samps) {
y <- runif(1)
i <- i + 1
u <- runif(1)
if (u < f.x(y) / 2.0736) {
n <- n + 1
samps[n] <- y
}
}
return(i)
}
Usage:
result <- replicate(10, getValue())

Function inputting all values into a matrix

I am having trouble with my function. When I call the function, it only seems to have looped through first value in my for loop and does not continue to fill my matrix. Here is the code. The output should be a matrix filled with 1's.
binfunction <- function(y) { #Set up a function that takes a vector input and puts the elements into bins
L <- length(y)
x <- c(0, cumsum(y))
U <- runif(1, min = 0 , max = sum(y))
for(i in 1:L) {
if(x[i] <= U && x[i+1] > U){
return(i)
}
}
}
randomgraph <- function(n, beta) {
mat <- matrix(0,n,n)
mat[1,2] <- 1
mat[2,1] <- 1
for(i in 3:n) { #Loop that fills matrix
degvect <- colSums(mat[ , (1:(i-1))])
degvect <- degvect^(beta)
j <- binfunction(degvect)
mat[i,j] <- 1
mat[j,i] <- 1
return(mat)
}
}

Retrieve list elements returned by a function in loop

I need to retrieve elements of list returned by a function in a loop and create a matrix using those list elements
Function:
function(med, days){
i <- 0
cnt = 1
lCnt = 1
value <- 0
fx <- 0
t <- 0
flag <- 0
daysList <- NULL
valuesList <- NULL
for(i in days){
lambda = ((0.693)/(med*30.475))
fx[cnt] <- c(1 - exp(-lambda*(i*7)))
if(cnt == 1){
prob = rbinom(1,1,fx[cnt])
}else{
t[cnt] <- ((fx[cnt]-fx[cnt - 1])/(1-fx[cnt-1]))
prob = rbinom(1,1,t[cnt])
}
if(cnt == 1){
tmp = days[cnt]
}else{
tmp = days[cnt] - days[cnt -1]
}
if(prob == 0 && flag == 0){
value = value + tmp
valuesList[lCnt] <- prob
}else{
if(flag == 0){
value = value + tmp
valuesList[lCnt] <- prob
flag <- 1
}else{
valuesList[lCnt] <- 'E'
}
}
daysList[lCnt] <- days[cnt]
lCnt = lCnt + 1
if(flag == 0){
cnt = cnt + 1
}
}
ret <- list('rDays' = daysList,'rValues' = valuesList)
return(ret)
}
Now I want to repeat this function for different inputs, so I used for loop as follows:
for(i in 1:300){
days1=c(rnorm(8,mean=56,sd=3))
days=cumsum(days1)
res[i] <- getMedData (med,days)
}
At the end I want two matrices one contains rDays returned by function and another with rValues
Can anyone please help me to create matrix in such format, Since I am new to R I am not able to find best way to do it
Finally Found the Way
Written loop which calls function as follows (I dont know if this is a right way or not but It worked for me :p)
for(i in 1:300){
days1=c(rnorm(8,mean=56,sd=3))
days=cumsum(days1)
a <- getMedData (med,days)
for(j in 1:length(days)){
resVal[i,j] = a[[1]][j]
resProb[i,j] = a[[2]][j]
}}

Trouble with infinite for - repeat loop in R

I have generated an infinite loop and don't know how to fix it.
I essentially want to go through the data frame rnumbers and generate rstate2 with 1, -1, or 0 depending on what is in rnumbers
The function step_generator is getting stuck at the repeat function. I am not sure how to make the code put -1 in rstate2 if rnumber is less than C and then repeat an ifelse function for the next rows until a value of D or greater is obtained. Once D is obtained exit the repeat function and go back into the original for loop.
Here is my code:
rnumbers <- data.frame(replicate(5,runif(20000, 0, 1)))
dt <- c(.01)
A <- .01
B <- .0025
C <- .0003
D <- .003
E <- .05
rstate <- rnumbers # copy the structure
rstate[] <- NA # preserve structure with NA's
# Init:
rstate[1, ] <- c(0)
step_generator <- function(col, rnum){
for (i in 2:length(col) ){
if( rnum[i] < C) {
col[i] <- -1
repeat {
ifelse(rnum[i] < E, -1, if(rnum[i] >= D) {break})
}
}
else { if (rnum[i] < B) {col[i] <- -1 }
else {ifelse(rnum[i] < A, 1, 0) } }
}
return(col)
}
# Run for each column index:
for(cl in 1:5){ rstate[ , cl] <-
step_generator(rstate[,cl], rnumbers[,cl]) }
Thanks for any help.
The problem is that you are not increasing i inside repeat loop, so basically you are testing the same i all the time, and because rnum[i] < C (from if condition) it will always be rnum[i] < E since C < E, and loop never breaks.
However, if you increase i inside repeat it still will come back to value resulting from for loop, so you have to do it in different way, for example using while loop. I'm not exactly sure if I understand what you are trying to do, but basing on your description I've made this function:
step_generator <- function(col, rnum){
i <- 2
while (i <= length(col)){
if (rnum[i] < C) {
col[i] <- -1
while ((i < length(col)) & (rnum[i + 1] < D)){
i <- i + 1
col[i] <- -1
}
} else if (rnum[i] < B){
col[i] <- -1
} else if (rnum[i] < A){
col[i] <- 1
} else {
col [i] <- 0
}
i <- i + 1
}
return(col)
}

Resources