I would like to have a vector res with length 200, which includes 20 times repetition of random generation values divided by 2 which is r[i], how can I get this in R?I wrote the following code but it is just save each iteration values,not the whole iterations.
r = rep(0, 10)
res = matrix(0, nrow=200, ncol=1)
for(j in 1:20){
for(i in 1:10){
x = rnorm(10, 0, 1)
r[i] = x/2
}
res = rbind(r)
}
as Roland said in a comment to your question writing two loops for this isn't a good practice. However, you can do it like this
res = rep(0, 200)
r = rep(0, 10)
for(j in 1:20){
for(i in 1:10){
x = rnorm(1, 0, 1)
r[i] = x/2
}
res[((j-1)*10+1):(j*10)] = r
}
As for your solution, there were some problems:
There is no need to define a matrix res = matrix(0, nrow=200, ncol=1) if you only need a vector
rnorm(10,0,1) returns a vector of 10 values so assigning it to r[i] (which takes only one value) isn't correct
rbind is used to connect two vectors/matrices/... by rows so using it with only one parameter doesn't really make a sense here
Related
i need to be able to use the 20 vectors in later caluclations ,so i want to create a 20x20 matrix which i can store each line from my code into a row,or if you can suggest a better way to be able to reference the code.
lambda=12
mu=2
answer = numeric(20)
k = 0
for (i in 1:20) {
Pi_i <- numeric(i)
m <- 1:i
k = k+((1/factorial(i)*(lambda/mu)^i))
for (j in m) {
Pi_i[j] = (k^-1)*((lambda/mu)^j)/factorial(j)
}
cat(Pi_i,"\n\n")
}
You could create an empty 20 x 20 matrix and write each vector into the ith row. You cannot have empty cells in a matrix, so you will have to append the correct number of NA values to the end of each vector:
lambda=12
mu=2
answer = numeric(20)
k = 0
result <- matrix(0, ncol = 20, nrow = 20)
for (i in 1:20) {
Pi_i <- numeric(i)
m <- 1:i
k = k+((1/factorial(i)*(lambda/mu)^i))
for (j in m) {
Pi_i[j] = (k^-1)*((lambda/mu)^j)/factorial(j)
}
result[i,] <- c(Pi_i, rep(NA, 20 - i))
}
result
I know I can use expand.grid for this, but I am trying to learn actual programming. My goal is to take what I have below and use a recursion to get all 2^n binary sequences of length n.
I can do this for n = 1, but I don't understand how I would use the same function in a recursive way to get the answer for higher dimensions.
Here is for n = 1:
binseq <- function(n){
binmat <- matrix(nrow = 2^n, ncol = n)
r <- 0 #row counter
for (i in 0:1) {
r <- r + 1
binmat[r,] <- i
}
return(binmat)
}
I know I have to use probably a cbind in the return statement. My intuition says the return statement should be something like cbind(binseq(n-1), binseq(n)). But, honestly, I'm completely lost at this point.
The desired output should basically recursively produce this for n = 3:
binmat <- matrix(nrow = 8, ncol = 3)
r <- 0 # current row of binmat
for (i in 0:1) {
for (j in 0:1) {
for (k in 0:1) {
r <- r + 1
binmat[r,] <- c(i, j, k)}
}
}
binmat
It should just be a matrix as binmat is being filled recursively.
I quickly wrote this function to generate all N^K permutations of length K for given N characters. Hope it will be useful.
gen_perm <- function(str=c(""), lst=5, levels = c("0", "1", "2")){
if (nchar(str) == lst){
cat(str, "\n")
return(invisible(NULL))
}
for (i in levels){
gen_perm(str = paste0(str,i), lst=lst, levels=levels)
}
}
# sample call
gen_perm(lst = 3, levels = c("x", "T", "a"))
I will return to your problem when I get more time.
UPDATE
I modified the code above to work for your problem. Note that the matrix being populated lives in the global environment. The function also uses the tmp variable to pass rows to the global environment. This was the easiest way for me to solve the problem. Perhaps, there are other ways.
levels <- c(0,1)
nc <- 3
m <- matrix(numeric(0), ncol = nc)
gen_perm <- function(row=numeric(), lst=nc, levels = levels){
if (length(row) == lst){
assign("tmp", row, .GlobalEnv)
with(.GlobalEnv, {m <- rbind(m, tmp); rownames(m) <- NULL})
return(invisible(NULL))
}
for (i in levels){
gen_perm(row=c(row,i), lst=lst, levels=levels)
}
}
gen_perm(lst=nc, levels=levels)
UPDATE 2
To get the expected output you provided, run
m <- matrix(numeric(0), ncol = 3)
gen_perm(lst = 3, levels = c(0,1))
m
levels specifies a range of values to generate (binary in our case) to generate permutations, m is an empty matrix to fill up, gen_perm generates rows and adds them to the matrix m, lst is a length of the permutation (matches the number of columns in the matrix).
I would like to iterate through vectors of values and calculate something for every value while being within a function environment in R. For example:
# I have costs for 3 companies
c <- c(10, 20, 30)
# I have the same revenue across all 3
r <- 100
# I want to obtain the profits for all 3 within one variable
result <- list()
# I could do this in a for loop
for(i in 1:3){
result[i] <- r - c[i]
}
Now lets assume I have a model that is very long and I define everything as a function which is to be solved with various random draws for the costs.
# Random draws
n <- 1000
r <- rnorm(n, mean = 100, sd = 10)
c1 <- rnorm(n, mean = 10, sd = 1)
c2 <- rnorm(n, mean = 20, sd = 2)
c3 <- rnorm(n, mean = 30, sd = 3)
X <- data.frame(r, c1, c2, c3)
fun <- function(x){
r <- x[1]
c <- c(x[2], x[3], x[4])
for(i in 1:3){
result[i] <- r - c[i]
}
return(result)
}
I could then evaluate the result for all draws by iterating through the rows of randomly sampled input data.
for(j in 1:n){
x <- X[j,]
y <- fun(x)
}
In this example, the output variable y would entail the nested result variable which comprises of the results for all 3 companies. However, my line of thinking results in an error and I think it has to do with the fact that I try to return a nested variable? Hence my question how you guys would approach something like this.
I would suggest rethinking your coding approach. This is a very un-R-like way of doing things.
For example, the first for loop can be written much more succinctly as
x <- c(10, 20, 30)
r <- 100
result <- lapply(-x, `+`, r)
Then fun becomes something like
fun <- function(x) lapply(-x[-1], `+`, x[1])
To then operate over the rows of a data.frame (which is what you seem to do in the last step), you can use something like
apply(X, 1, fun)
where the MARGIN = 1 argument in apply ensures that you are applying a function per row (as opposed to per column).
Here's an approach using your function and a for loop:
# Random draws
n <- 1000
r <- rnorm(n, mean = 100, sd = 10)
c1 <- rnorm(n, mean = 10, sd = 1)
c2 <- rnorm(n, mean = 20, sd = 2)
c3 <- rnorm(n, mean = 30, sd = 3)
X <- data.frame(r, c1, c2, c3)
result <- list()
fun <- function(x){
r <- x[[1]]
c <- c(x[[2]], x[[3]], x[[4]])
for(i in 1:3){
result[i] <- r - c[i]
}
return(result)
}
# Create a list to store results
profits <- rep(rep(list(1:3)),nrow(X))
# Loop throuhg each row of dataframe and store in profits.
for(i in 1:nrow(X)){
profits_temp <-
fun(list(X[i,"r"],X[i,"c1"],X[i,"c2"],X[i,"c3"]))
for(j in 1:3)
profits[[i]][[j]] <- profits_temp[[j]]
}
# Eye results
profits[[1]]
#> [1] 93.23594 81.25731 70.27699
profits[[2]]
#> [1] 80.50516 69.27517 63.36439
I am trying to generate a matrix sz by first applying a binomial, then adding values from the corresponding column of pombe_new_subs and this combined value being input as size for the following column.
After many frustrations, the following code is what I've ended up with and it just doesn't work - problems I'm coming across are;
# Error in sz[j, i + 1] = sz[, i] + pombe_new_subs[, i] :
# number of items to replace is not a multiple of replacement length
pombe_new_subs <- rmultinom(3, 15, prob = c(0.3, 0.3, 0.3))
randomdiv <- function(nchrom, ndivs, size) {
sz <- matrix(nrow = nchrom, ncol = ndivs)
for (j in 1:nchrom) {
n <- size
for (i in 1:ndivs) {
n <- rbinom(1, n, 0.5)
sz[j,i] <- n
}
sz[j,i+1] = sz[ ,i] + pombe_new_subs[ ,i]
sz[j, i+1] <- n
}
return (sz)
}
randomdiv(3, 3, 10)
I know this is probably a fairly simple looping exercise but frustration has entirely taken over.
I have the following script:
randomdiv <- function(ncells, ndivs, size, accuracy) { sz <- matrix(nrow = ncells, ncol = ndivs)
for (j in 1:ncells) {
total_subunits <- size
for (i in 1:ndivs)
{
accurate_subunits <- (size * accuracy)
random_subunits <- round(size - accurate_subunits)
random_inh <- rbinom(1, random_subunits, 0.5)
accurate_inh <- (accurate_subunits / 2)
total_inh <- 2 * (random_inh + accurate_inh)
sz[j,i] <- total_inh
total_subunits <- total_inh
}
}
return (do.call(rbind, replicate(100, sz, simplify = FALSE)))
}
Such that I thought randomdiv(5, 20, 10, 0) would return a matrix with 500 rows, where the original sz matrix had been replicated 100 times. In fact, this is the case. However, the replicates are identical rather than each replicate being a fresh generation of data, which is what I need.
Any ideas how I can make sure that each replicate is a new matrix, not literally a replicate of the first one to be generated?