I am a beginner in R and I am given the following problem to code:
Let
and
be the summations I am trying to recreate into R.
Right now this is my code for the first summation (code snippet):
z <- 1:J
L<-1000
D<-0
for(k in z){
for(j in D:D+L-1){
X[k] = 1/L*sum(X[j])
}
}
I had no idea how to create latex formulas in the questions so if you run the code snippets you see the formulas I am trying to recreate in R.
My question is, am I on the right path? I am not sure how to use the for loop to create the summation.
J <- 5
L <- 100
D <- 1 # in R we start to count at 1 (one). (thanks to Darren)
x <- matrix(1:(L*J), nrow = length(D:(D+L-1)), ncol = J)
funXj_ <- function(j, D, L) sum(x[D:(D+L-1), j], na.rm = T)
X_ <- sapply(1:J, funXj_, D = D, L = L)
#5050 15050 25050 35050 45050
I believe your x_j^t is some sort of 2-Dimensional array. (so I took a matrix as example)
we're of course free to alter our borders:
J as 4, D as 2, L as 80
sapply(1:4, funXj_, D = 2, L = 80)
Related
I need to simulate the probabilities that are computed using the function transitionProbability1D from isingLenzMC package. I want to simulate them for 10 values of bF at once and receive a vector of results but still receive only one number and I dont know why. Here is my code
N <- 100
conf0 <- genConfig1D(N)
conf1 <- flipConfig1D(conf0)
# transition probability at J=H=1/kBT=1.0, 1= p-ty metropolis 2=glauber
bF <- 1:10
J <- h <- rep(1,10)
# HERE IT DOESNT WORK EVEN THOUGHT bF IS A VECTOR
transitionProbability1D(bF, conf0, conf1, J, h, 1)
>> 0.298615
You might want to look at how to vectorize a function.
On your example, the following would probably give you what you expect:
library(isingLenzMC)
N <- 100
conf0 <- genConfig1D(N)
conf1 <- flipConfig1D(conf0)
# transition probability at J=H=1/kBT=1.0, 1= p-ty metropolis 2=glauber
bF <- 1:10
# Here I changed these inputs to single values
J <- h <- 1
# HERE IT DOESNT WORK EVEN THOUGHT bF IS A VECTOR
transitionProbability1D(bF, conf0, conf1, J, h, 1)
# Vectorize on the first argument
transitionProbability1D_vectorized <- Vectorize(transitionProbability1D, vectorize.args = "ikBT")
# Now there are as many results as input values
transitionProbability1D_vectorized(ikBT = bF, x = conf0, xflip = conf1, J = J, H = h, probSel = 1)
You could also use a (for) loop!
How to find sum of i<j (i,j = 1 to 25) of i without using for loop in R language.
This equation is what I am trying to code exactly, I need to get the index of both i and j and calculate sum of determination from there.
{(x_i, j_i)}i = 1 to 25
We can use outer
sum(outer(i, j, FUN = `<`))
If we need to find the sum of 'x'
sum(matrix(x, 25, 25)[outer(x, x, FUN = `<`)])
data
i <- 1:25
j <- 1:25
x <- rnorm(25)
For vector x, you can try the code below
sum(cumsum(x)[-length(x)])
# DATA
set.seed(42)
n = 25
v = 1:n
x = rnorm(n)
sum(rep(v, n) < rep(v, each = n))
sum(rep(x, n)[rep(v, n) < rep(v, each = n)])
If I have a function
estimator <- function(A,B) {
A*(B+23)
}
How can I reverse this function to find the value of A for B as a sequence between 0 and 120 (B=1,2,3,4,...,120) that would give a fixed result, say C = 20?
I would use it to map the values for which satisfy the equation A*(B+23)= C = 20 with B being a list b.list between 0 and 120, for c.list, of different C?
b.list <- seq(0,120,by=1)
c.list <- tibble(seq(10,32,by=2))
In the end, I would like to plot the lines of curves of the function for different C using purrr or similar.
I.e.: Given that the height of a tree in metres at age 100 will follow the function, C = A*(B+23), solve for A that will give the result C=10 when B, Age is a list of years between 0 and 120?
Here's a link showing what I'm trying to make!
Here's another one
Many thanks!
For the inverse it is a quick inversion :
A = C/(B+23)
One answer could be :
B <- seq(0, 120)
C <- seq(10, 32, 2)
A <- matrix(0,
nrow = length(B),
ncol = length(C))
for(i in 1:ncol(M)){
A[,i] <- C[i] / (B + 23)
}
matplot(B, A, type ="l", col = "black")
In case of a more complex function indeed you need an automatic solving problem. One way is to see it like an optimisation problem where you want to minimise the distance from C :
B <- seq(1, 120)
C <- seq(10, 32, 2)
A <- matrix(0,
nrow = length(B),
ncol = length(C))
fct <- function(A, B, C){
paramasi <- 25
parambeta<- 7395.6
paramb2 <- -1.7829
refB <- 100
d <- parambeta*(paramasi^paramb2)
r <- (((A-d)^2)+(4*parambeta*A*(B^paramb2)))^0.5
si_est <- (A+d+r)/ (2+(4*parambeta*(refB^paramb2)) / (A-d+r))
return(sum(si_est - C)^2)}
for(c in 1:length(C)){
for(b in 1:length(B)){
# fixe parameters + optimisation
res <- optim(par = 1, fn = fct, B = B[b], C = C[c])
A[b, c] <- res$par
}
}
matplot(B, A, type = "l", col = "black")
You need to be careful because in your case I think that you could find an analytical formula for the inverse which would be better.
Good luck !
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 am trying to find a way to efficiently use permutations of a vector in R without blowing up my computer. This is what I am trying to do:
n = 3 # I would need n>1000 instead, this is just to show what I am trying to achieve
t = 3
library(gtools)
m <- permutations(n = n, r = t, repeats.allowed = F, v = 1:n)
mm <- as.numeric(m)
df = data.frame()
for (i in 1:nrow(m)) {
mat <- matrix(0, nrow = ncol(m), ncol = n)
idx = m[i,]
mat[cbind(seq_along(idx), idx)] = 1
df = rbind(df, mat)
}
However using permutations, it is too time/memory consuming to work with large n (e.g. >1000). It looks like using "sample" is a great solution (proposed here):
v = 1:n
N <- t(replicate(length(v)^4, sample(v, t)))
# compare with: permutations(n = n, r = t, repeats.allowed = F, v = 1:n)
sum(duplicated(N))
m <- N[!(duplicated(N)), ] # then continue with code above
However, I am still unsure about the number of samples to take to be sure to cover all the possibilities. Does anybody have any ideas on number of samples, or how to make sure that all possibilities are covered? Thank you!