R : Changing values of variables after certain time - r
the question I am trying to ask is how to I change one of the values of my variables (noted as LO$M in my list) after I pass a certain time.
The thing I am trying to achieve is that after 20,000 seconds passing I would like to change my value of Lac to the value of Lac at time 20,0000 +10,000
So at t = 20,000, Lac = Lac + 10,000
The issue I am having with my code is that within my if command I have if tt>= 20000, but this leads to the issue that every value of Lac after 20,000 being increased by 10,000 when what i want is that the FIRST value after 20,000 be increased by 10,000.
Basically, after 20,000 of my experiment passing I am trying to inject 10,000 more Lac into the experiment.
My code is given below:
LO = list()
LO$M = c(i = 1, ri = 0, I = 50, Lac = 20, ILac = 0, o = 1, Io = 0, RNAP = 100, RNAPo = 0, r = 0, z = 0)
LO$Pre = matrix(c(1,0,0,0,0,0,0,0,0,0,0,
0,1,0,0,0,0,0,0,0,0,0,
0,0,1,1,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,
0,0,1,0,0,1,0,0,0,0,0,
0,0,0,0,0,0,1,0,0,0,0,
0,0,0,0,0,1,0,1,0,0,0,
0,0,0,0,0,0,0,0,1,0,0,
0,0,0,0,0,0,0,0,1,0,0,
0,0,0,0,0,0,0,0,0,1,0,
0,0,0,1,0,0,0,0,0,0,1,
0,1,0,0,0,0,0,0,0,0,0,
0,0,1,0,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,1,0,
0,0,0,0,0,0,0,0,0,0,1), ncol=11, byrow=TRUE)
LO$Post = matrix(c(1,1,0,0,0,0,0,0,0,0,0,
0,1,1,0,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,
0,0,1,1,0,0,0,0,0,0,0,
0,0,0,0,0,0,1,0,0,0,0,
0,0,1,0,0,1,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,0,0,
0,0,0,0,0,1,0,1,0,0,0,
0,0,0,0,0,1,0,1,0,1,0,
0,0,0,0,0,0,0,0,0,1,1,
0,0,0,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,
0,0,0,1,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0), ncol=11, byrow=TRUE)
LO$h = function(x,t,th=c(0.02,0.1,0.005,0.1,1,0.01,0.1,0.01,0.03,0.1,1e-05,0.01,0.002,0.01,0.001))
{
with(as.list(c(x, th)), {
return(c(th[1]*i, th[2]*ri, th[3]*I*Lac, th[4]*ILac, th[5]*I*o, th[6]*Io, th[7]*o*RNAP,
th[8]*RNAPo, th[9]*RNAPo, th[10]*r, th[11]*Lac*z, th[12]*ri, th[13]*I,
th[13]*ILac, th[14]*r, th[15]*z))
})
}
gillespie1 = function (N, n, ...)
{
tt = 0
x = N$M
S = t(N$Post - N$Pre)
u = nrow(S)
v = ncol(S)
tvec = vector("numeric", n)
xmat = matrix(ncol = u, nrow = n + 1)
xmat[1, ] = x
for (i in 1:n) {
h = N$h(x, tt, ...)
tt = tt + rexp(1, sum(h))
j = sample(v, 1, prob = h)
x = x + S[, j]
tvec[i] = tt
xmat[i + 1, ] = x
if( tt >=20000){
x[4] = x[4] +10000
}
}
return(list(t = tvec, x = xmat))
}
newout = gillespie1(LO,200000)
matplot(newout$x[,4], type="l", lwd=0.25, col="grey")
I don't have a high enough reputation to attach images, but it should look something like this:
https://gyazo.com/0ffd940a22df23b2ccfdf4a17e85dca8
Sorry if this isn't clear. Thanks
In this example, you have the function myTask(). When you call execMyTask(), you will execute myTask()once, and after that, you will execute it at random intervals between 1 to max_wait milliseconds. When you get tired, you can kill the task with tclTaskDelete().
library(tcltk2)
myTask <- function() cat("some task!\n")
id = "execMyTask"
execMyTask <- function(max_wait = 3000) {
id <- toString(match.call()[[1]])
myTask()
wait = sample(1:max_wait, 1)
cat("Waiting", wait, "miliseconds\n") # replace with your function
if (is.null(tclTaskGet(id))) {
tclTaskSchedule(wait=wait, execMyTask(), id=id, redo = TRUE)
} else {
tclTaskChange(wait=wait, execMyTask(), id=id, redo = TRUE)
}
}
execMyTask()
tclTaskDelete(id)
So far, there is a little problem with this approach, because we can not supply arguments to the function fun in tclTaskChange().
Related
R object does not exist
I am running the following loop. The first loop is this: cliff = function(a, b, c, d, x0, y0, n){ tab = data.frame(NA, nrow = n+1, ncol = 2) colnames(tab) = c("x", "y") tab[1,1:2] = c(x0, y0) for(i in 1:n){ i = i + 1 tab[i,1] = sin(a*tab[(i-1),2]) + c*cos(a*tab[(i-1),1]) tab[i,2] = sin(b*tab[(i-1),1]) + d*cos(b*tab[(i-1),2]) } return(round(tab[,1:2], 3)) } This is just some loop I made (I know it's not the best) that runs through this recursive operation that generates new x and y values from previous ones. My main concern is this loop: val = c(10,100,1000,10000,100000) tab2 = data.frame(n = rep(NA, length(val)), Time = rep(NA, length(val))) i = 1 for(n in val){ sT = Sys.time() cliff(a = 1, b = 1, c = 2, d = 3, x0 = 0, y0 = 0, n) cat() eT = Sys.time() mytime = eT - sT if(attributes(mytime)$units == "mins"){ tab2$Time[i] = mytime*60 } else{ tab2$Time[i] = mytime } tab2$n[i] = n; i = i + 1 } tab2 Because this loop takes a good 20 minutes to run, I ran it one time to have tab2 saved as a data frame so it can be used in the future. However, when I try and knit the pdf, I get the following error: Error in eval(expr, envir, enclos) : object 'tab2' not found Why is this happening? When I check in my stored objects, it is there, and when I use exists("tab2") I get TRUE. So why does RMarkdown say this does not exist?
Creating a Table out of a While Loop in R
I am trying to make a table from a while loop. Basically, I want to make a while loop where the value of r increases by 1 and repeats this until the inequality is met. But in addition to that, I want to combine these values into a table with three columns: the value of r, the value of w, and the value of rhs (rounded to 3 decimal places). ```{r} al = 0.10; n = 30; a = 3; b = 5; r = 2; int = 8; h = (int/2); msE = 19.19 table = function(MSE, V, H, alpha = al, r = 2){ rhs = h^2*r/((V-1)*MSE) w = qf(alpha, V-1, V*(r-1), lower.tail = FALSE) g = data.frame(r, round(w, 3), round(rhs, 3)) while(w > rhs){ r = r+1 rhs = h^2*r/((V-1)*MSE) w = qf(alpha, V-1, V*(r-1), lower.tail = FALSE) g = data.frame(r, round(w, 3), round(rhs, 3)) } rbind(g) } table(MSE = msE, V = a*b, H = h) ``` I figured it would go something like this, but this only prints out the last value of r before the loop ends (it ends at 26), which results in a "table" that only has one row. I would like a table with 24 rows (since it starts at r = 2). Any help would be appreciated!
Perhaps this might help: al = 0.10; n = 30; a = 3; b = 5; r = 2; int = 8; h = (int/2); msE = 19.19 table = function(MSE, V, H, alpha = al, r = 2){ rhs = h^2*r/((V-1)*MSE) w = qf(alpha, V-1, V*(r-1), lower.tail = FALSE) g = data.frame(r, round(w, 3), round(rhs, 3)) gn = data.frame(r, round(w, 3), round(rhs, 3)) while(w > rhs){ r = r+1 rhs = h^2*r/((V-1)*MSE) w = qf(alpha, V-1, V*(r-1), lower.tail = FALSE) g = data.frame(r, round(w, 3), round(rhs, 3)) gn <- rbind(gn,g) } return(gn) } table(MSE = msE, V = a*b, H = h)
A slightly different approach, eliminating the need for an interim data frame and for rbind(). Commented in the code. # your parameters al <- 0.10; n <- 30; a <- 3; b <- 5; int <- 8; h <- (int/2); msE <- 19.19 # your function definition (name changed to avoid confusion / conflict with existing R function) tabula <- function(MSE, V, H, alpha = al, r = 2) { g <- data.frame( N = 0, W = 1, RHS = 0 ) # initiate data frame, values set # so that the while condition is met # the while function populates the data frame cell by cell, # eliminating the need for an interim data.frame and rbind() while( g[ r - 1, "W" ] > g[ r - 1, "RHS" ] ) # check condition in the last data frame row { # write values in a new row g[ r, "N" ] <- r g[ r, "W" ] <- round( qf( alpha, V - 1, V * ( r - 1 ), lower.tail = FALSE ), 3 ) g[ r, "RHS" ] <- round( h^2 * r / ( ( V - 1 ) * MSE ), 3 ) r <- r + 1 # increment row counter } return( g[ -1, ] ) # return the data frame, removing the initial row } tabula( MSE = msE, V = a * b, H = h )
Efficient code to map genotype matrix in R
Hi I want to convert a matrix of genotypes, encoded as triples to a matrix encoded as 0, 1, 2, i.e. c(0,0,1) <-> 0; c(0,1,0) <-> 1; c(0,0,1) <-> 2 First here is some code to generate the matrix that needs to be reduced. # generate genotypes expand.G = function(n,p){ probs = runif(n = p) G012.rows = matrix(rbinom(2,prob = probs,n=n*p),nrow = p) colnames(G012.rows) = paste('s',1:n,sep = '') rownames(G012.rows) = paste('g',1:p, sep = '') G012.cols = t(G012.rows) expand.geno = function(g){ if(g == 0){return(c(1,0,0))} if(g == 1){return(c(0,1,0))} if(g == 2){return(c(0,0,1))} } gtype = c() for(i in 1:length(c(G012.cols))){ gtype = c( gtype, expand.geno(c(G012.cols)[i]) ) } length(gtype) G = matrix(gtype,byrow = T, nrow = p) colnames(G) = paste('s',rep(1:n,each = 3),c('1','2','3'),sep = '') rownames(G) = paste('g',1:p, sep = '') print(G[1:10,1:15]) print(G012.rows[1:10,1:5]) return(G) } The output has 3n columns and p rows, where n is sample size and p is number of genotypes. Now we can reduce the matrix back to 0,1,2 coding with the following functions reduce012 = function(x){ if(identical(x, c(1,0,0))){ return(0) } else if(identical(x, c(0,1,0))){ return(1) } else if(identical(x, c(0,0,1))){ return(2) } else { return(NA) } } reduce.G = function(G.gen){ G.vec = mapply(function(i,j) reduce012(as.numeric(G.gen[i,(3*j-2):(3*j)])), i=expand.grid(1:(ncol(G.gen)/3),1:nrow(G.gen))[,2], j=expand.grid(1:(ncol(G.gen)/3),1:nrow(G.gen))[,1] ) G = matrix(G.vec, nrow = ncol(G.gen)/3, ncol = nrow(G.gen)) colnames(G) = rownames(G.gen) return(G) } reduce.G.loop = function(G.gen){ G = matrix(NA,nrow = ncol(G.gen)/3, ncol = nrow(G.gen)) for(i in 1:nrow(G.gen)){ for(j in 1:(ncol(G.gen)/3)){ G[j,i] = reduce012(as.numeric(G.gen[i,(3*j-2):(3*j)])) } } colnames(G) = rownames(G.gen) return(G) } The output is n rows by p columns. It is incidental, but intentional, that the matrix encoded as 0,1,2 is the transpose of the matrix encoded as triples. The code is not particularly fast. What is bothering me is that the the timing goes with n^2. Can you explain or supply more efficient code? G = expand.G(1000,20) system.time(reduce.G(G)) system.time(reduce.G.loop(G)) G = expand.G(2000,20) system.time(reduce.G(G)) system.time(reduce.G.loop(G)) G = expand.G(4000,20) system.time(reduce.G(G)) system.time(reduce.G.loop(G))
You can simply make an accessor lookup table: decode <- array(dim = c(3, 3, 3)) decode[cbind(1, 0, 0) + 1] <- 0 decode[cbind(0, 1, 0) + 1] <- 1 decode[cbind(0, 0, 1) + 1] <- 2 And then, just do: matrix(decode[matrix(t(G + 1), ncol = 3, byrow = TRUE)], ncol = nrow(G)) This full vectorized R version will give you the same matrix, without dimnames and super fast. Yet, if you have much larger matrices, you should really use Rcpp for both memory and timing issues.
This seems to be a about three times faster than your version (renamed reduce.G.orig): reduce.G <- function(G) { varmap = c("100"=0, "010"=1, "001"=2) result <- do.call(rbind, lapply(1:(ncol(G)/3)-1, function(val) varmap[paste(G[,3*val+1], G[,3*val+2], G[,3*val+3], sep="")])) colnames(result) <- rownames(G) result } system.time(reduce.G(G)) # user system elapsed # 0.156 0.000 0.155 system.time(reduce.G.orig(G)) # user system elapsed # 0.444 0.000 0.441 identical(reduce.G(G), reduce.G.orig(G)) # [1] TRUE
Stepfun function markov
Don't be scared by my long code. What i am wondering is about the last part, the plot(step fun... part. When i enter this into Rstudio i get "stepfun "x" must be ordered increasingly" Is there any1 here who knows what I have to do to finish this correctly? bd_process <- function(lambda, mu, initial_state = 0, steps = 100) { time_now <- 0 state_now <- initial_state time <- 0 state <- initial_state for (i in 1:steps) { if (state_now == 3) { lambda_now <- 0 } else { lambda_now <- lambda } if (state_now == 0) { mu_now <- 0 } else { mu_now <- mu } time_to_transition <- rexp(mu, rate = 1) + rexp(lambda, rate = 1) X <- rexp(mu, rate = 1) Y <- rexp(lambda, rate = 1) if (X < Y) { state_now <- state_now - 1 } else { state_now <- state_now + 1 } time_now <- time_now + time_to_transition time <- c(time, time_now) state <- c(state, state_now) } list(time = time, state = state) } set.seed(19930628) proposal1 <- bd_process(lambda = 2, mu = 10) proposal2 <- bd_process(lambda = 6, mu = 10) proposal3 <- bd_process(lambda = 10, mu = 10) time1 <- proposal1$time state1 <- proposal1$state plot(stepfun(time1[-1], state1), do.points = FALSE, xlab = "Tid", ylab = "Tillstånd", main = "", yaxt = "n") axis(2, at = c(0, 1, 2, 3), las = 2)
I don't know what your code is doing but you've asked us not to worry about that. At the moment it appears that you have only constructed "time intervals" but now need to "stack them together" or "integrate" them along a proper time axis. In order to plot a simulation of a stepfunction, you should be using cumsum to construct an increasing time1 vector. Because the "time" and "state" variables are of such different lengths a quick fix to the function arguments is trimming the time1 vector so it is the correct length for the state1 variable, and you get no error with: plot(stepfun(cumsum(time1[2:101]), state1), do.points = FALSE, xlab = "Tid", ylab = "Tillstånd", main = "", yaxt = "n") axis(2, at = c(0, 1, 2, 3), las = 2) Maybe if you "march step-by-step" through the code and explain the code (to yourself and the rest of us) using comments you will figure out why you have 10 times as many time1's as you have state1's. I suspect it may have something to do with using "mu" as the first argument to rexp(mu, rate = 1). The first argument to random number generators in R is usually a positive integer that determines length (the number of random numbers) from the distribution.
Bayesian R Programming
binomial <- function(nmax = 100, thr = 0.95, alpha = 1, beta = 1, p_true = 0.5, p_0 = 0.5){ for(j in seq.int(nmax, 0)){ if(pbeta(q = p_0, shape1 = alpha + j, shape2 = beta + nmax - j, lower.tail = FALSE) < thr){ targetatnmax <- j + 1 } else { print( break } } result <- list(Success = Success, targeratnmax = targetatnmax) return(result) } res = binomial(nmax,thr,alpha,beta,p_true,p_0) res In my program I am trying to find the number of successes needed to exceed 0.95 thr. I am trying to use a for loop with if else statements but when I run it I don't get the value I need. I know my value should be 59 but I cannot seem to get this. I know the code seems really messy but its only because I have been playing around with it for hours. PLEASE ANY HELP
Here is your code after clean-up: binomial <- function(nmax = 100, thr = 0.95, alpha = 1, beta = 1, p_true = 0.5, p_0 = 0.5){ targetatnmax <- 0 for(j in seq.int(0,nmax)){ if(pbeta(q = p_0, shape1 = alpha + j, shape2 = beta + nmax - j, lower.tail = FALSE) < thr){ targetatnmax <- j + 1 } else { break } } result <- list(targeratnmax = targetatnmax) return(result) } res = binomial() res #$targeratnmax #[1] 59 The main problem (other than the syntax errors and not existent objects) was that your loop ran from nmax to 0 instead of the other way arround. There is probably potential for optimization, but my understanding of the statistics is not good enough to really tackle that.