I have been trying to run this code (below here) and I have gotten that message "Error in if (temp[ii] == 0) { : missing value where TRUE/FALSE needed"...
temp = c(2.15, 3.5, 0, 0, 0, 1.24, 5.42, 6.87)
tm = length(temp)
for (i in 1:tm){
if (temp[i] == 0) {
counter3 = 1
last = temp[i - 1]
for (ii in i + 1:tm){
if (temp[ii] == 0) {
counter3 = counter3 + 1
}
if (temp[ii] != 0) {
nxt = temp[i + counter3]
}
}
}
}
Your problem is that temp[ii] is returning NA because ii goes out of bounds:
ii = i + 1:tm #Your declaration for ii
ii = 1:tm + 1:tm #Evaluates to
So ii will definitely be larger than tm (and therefore length(temp) at some point.
In order to better understand/debug for loops, consider printing just the indices:
for(i in 1:tm)
{
print(i)
for(ii in i + 1:tm)
print(ii)
}
At a guess I'm going to say that this is in R - if so I'm guessing that this line:
if (temp[i] == 0) (or temp[ii] == 0)
is resulting in an NA, and if conditions must have a TRUE or FALSE value.
Using a debugger if you can, I'd interrogate the value of temp[i] before the if block.
Difficult without knowing the language, but i think the issue is that the value in ii can be greater than the length of temp when i is at its upper bound. I'd have expected an index out of range or something similar but, without knowing the language, who knows! Hope you get your problem fixed.
Related
I made a loop to generate a Markov Chain. If the proposal does not satisfy a condition, I want to restart the iteration with a new proposal? Is there a way to do this? My current code is shown below for reference. Currently, it sets the current chain's value to the previous one. But I don't want that. I want it to just restart the "i". So if i=2, and the condition in line 4 is not satisfied, I then want it to stay at i=2 until it is satisfied. Thanks in advance.
ABC_MCMC<-function(n){
for (i in 2:n){
prop<-rnorm(1,mean=chain[i-1],sd=1)
if (ABC(prop)==T & prop>=0){
h_ratio<-(dgamma(prop,shape=prior_alpha,rate=prior_beta)/dgamma(chain[i-1],shape=prior_alpha,rate=prior_beta))*
(dnorm(x=chain[i-1],mean=prop,sd=1)/dnorm(x=prop,mean=chain[i-1],sd=1))
u<-runif(1)
if (min(1,h_ratio)>u) {chain[i]=prop} else {chain[i]=chain[i-1]}
}
else{chain[i]=chain[i-1]}
}
return(chain<<-chain)
}
This is more of a comment than of an answer but to keep the code formatting I'm posting as an answer.
Replace the code inside the for loop for the code below.
while(TRUE) {
prop <- rnorm(1, mean = chain[i - 1L], sd = 1)
if (ABC(prop) && prop >= 0) {
h_ratio<-(dgamma(prop,shape=prior_alpha,rate=prior_beta)/dgamma(chain[i-1],shape=prior_alpha,rate=prior_beta))*
(dnorm(x=chain[i-1],mean=prop,sd=1)/dnorm(x=prop,mean=chain[i-1],sd=1))
u<-runif(1)
if (min(1,h_ratio)>u) {chain[i]=prop} else {chain[i]=chain[i-1]}
break
} else {chain[i] <- chain[i-1]}
}
Edit
The function below seems to be what is asked for.
ABC_MCMC <- function(n){
for (i in 2:n){
# loops until condition (ABC(prop) & prop >= 0) is met
while(TRUE) {
prop <- rnorm(1, mean = chain[i-1], sd = 1)
if (ABC(prop) & prop >= 0) {
h_ratio <- (dgamma(prop, shape = prior_alpha, rate = prior_beta)/dgamma(chain[i - 1L], shape = prior_alpha, rate = prior_beta)) *
(dnorm(chain[i - 1L], prop, 1)/dnorm(prop, chain[i - 1L], 1))
u <- runif(1)
if (min(1, h_ratio) > u) {
chain[i] <- prop
} else {
chain[i] <- chain[i - 1L]
}
break
}
}
}
# function return value
chain
}
Do if statements not work for integrate? I have to do something much more complicated than this, but I am supplying this example because it isolated the problem.
Kernel = function(x){
if(abs(x)<1){
w = 1 - abs(x)
} else{
w = 0
}
return(w)
}
integrate(Kernel,
0,
1)
The error message:
the condition has length > 1 and only the first element will be used
Kernel = function(x){
pmax(1-abs(x), 0)
}
integrate(Kernel, 0, 1)
0.5 with absolute error < 5.6e-15
or even:
Kernel1 = function(x){
ifelse(abs(x)<1, 1-abs(x), 0)
}
integrate(Kernel1, 0, 1)
0.5 with absolute error < 5.6e-15
If you want to maintain the way you have written your function, you have to vectorize it:
Kernel2 = function(x){
ifelse(abs(x)< 1, 1-abs(x), 0)
if(abs(x)<1){
w = 1 - abs(x)
} else{
w = 0
}
return(w)
}
integrate(Vectorize(Kernel2), 0, 1)
0.5 with absolute error < 5.6e-15
Hi i just need some help understanding this line of code from a function to get prime numbers (see below for the whole function):
if (i == 2L || all(i %% 2L:ceiling(sqrt(i)) != 0))
What does i == 2L do as well as ceiling(sqrt(i)). This function basically just generates a vector of prime numbers or just returns the last prime number in the vector. I don't quite understand what those 2 sections are used for.
Normally i would just check for a prime number like this all(i %% 2:(i-1) !=0) So why are those two elements changed in the code?
get_prime <- function(n, all = TRUE, i = 1, primes = c()){
if ( n <= 0) {
stop("Not a valid number")
}
if (length(primes) < n) {
if (i == 2L || all(i %% 2L:ceiling(sqrt(i)) != 0)) {
get_prime(n, all = all, i = i + 1, primes = c(primes, i))
} else {
get_prime(n, all = all, i = i + 1, primes = primes)
}
} else {
if (all) {
return(primes)
} else {
return(tail(primes, 1))
}
}
}
Imagine you had to check if q=1,000,001 was a prime number.
The simplest way to do this is to check if any integer in [2, 1000000] is a factor of q.
Suppose a factor, f, of q does exist and it is not in [2, ceiling(sqrt(q))].
So f > ceiling(sqrt(q)) and q/f <= q/sqrt(q) = sqrt(q)
So whatever q/f is, it lies in [2, ceiling(sqrt(q))].
That's why you only need to check up to ceiling(sqrt(q))
I only get this error in attempting to knit in R Markdown to a Word document. The code runs fine elsewhere (in the Rscript).Also I have already had previous code showing:
numericScores = transform(correctedScores, beer2_score = as.numeric(beer2_score))
numericScores = transform(correctedScores, beer3_score = as.numeric(beer3_score))
numericScores = transform(correctedScores, beer4_score = as.numeric(beer4_score))
numericScores = transform(correctedScores, beer5_score = as.numeric(beer5_score))
numericScores = transform(correctedScores, beer6_score = as.numeric(beer6_score))
# testing to see if they are indeed numeric
sapply(numericScores, mode)
correctedGuesses = Guesses[complete.cases(Guesses), ]
str(correctedGuesses)
correctedGuesses
correctedScores = numericScores[complete.cases(numericScores), ]
str(correctedScores)
correctedScores
########
# trying to put scores in correct order
# first I will label the beers with their names
for(i in 1:45){
for(j in 2:7) {
if (Order[i,j] == 1) { Order[i, j] = "Miller"}
if (Order[i,j] == 2) { Order[i, j] = "Natural"}
if (Order[i,j] == 3) { Order[i, j] = "Keystone"}
if (Order[i,j] == 4) { Order[i, j] = "Busch"}
if (Order[i,j] == 5) { Order[i, j] = "Bud"}
if (Order[i,j] == 6) { Order[i, j] = "Miller"}
}
}
# Deleting the unused/unavailable Order rows
Order = Order[-c(4, 33),]
Miller_sc = 0
Natural_sc = 0
Keystone_sc = 0
Busch_sc = 0
Bud_sc = 0
B = c(
Miller_sc,
Natural_sc,
Keystone_sc,
Busch_sc,
Bud_sc )
for (i in 1:43) {
for (j in 2:7) {
if (Order[i,j] == "Miller") {B[1] = B[1] + correctedScores[i,j]}
if (Order[i,j] == "Natural") {B[2] = B[2] + correctedScores[i,j]}
if (Order[i,j] == "Keystone") {B[3] = B[3] + correctedScores[i,j]}
if (Order[i,j] == "Busch") {B[4] = B[4] + correctedScores[i,j]}
if (Order[i,j] == "Bud") {B[5] = B[5] + correctedScores[i,j]}
}
}
The error reads:
Error in B[3] + correctedScores[i, j]: non-numeric argument to binary
operator Calls: ... handle ->withCallingHandlers ->
withVisible -> eval -> eval Execution halted
The usual reason for an error like this is that the code in your document refers to a variable in your global environment. When you knit the document, it can't see that variable, so you get an error.
Most commonly that error would be some variation on "variable not found". You're getting a different error, so R is finding a variable with the right name somewhere else.
Without the full document, we can't tell you for sure what variable would be causing your problems. When I take a quick look at your script, I see these variables with no definitions:
correctedScores
beer2_score # etc., though these might be columns in correctedScores
Guesses
Order
I also notice that the first 4 lines of your script do nothing, since the 5th line overwrites their result.
I was asked to implement function that calculates n-dimensional matrix determinant using Laplace expansion. This involves recursion. I developed this:
minor<-function(A,i,j) {
return(A[c(1:(i-1),(i+1):dim(A)[1]),c(1:(j-1),(j+1):dim(A)[2])])
}
determinantRec<-function(X,k) {
if (dim(X)[1] == 1 && dim(X)[2] == 1) return(X[1][1])
else {
s = 0
for (i in 1:dim(X)[2]) {
s = s + X[k][i]*(-1)^(k+i)*determinantRec(minor(X,k,i),k)
}
return(s)
}
}
where k in determinantRec(X,k) function indicates which row I want to use Laplace expansion along of.
My problem is when I run determinantRec(matrix(c(1,2,3,4),nrow = 2,ncol = 2),1) this error appears:
C stack usage 7970628 is too close to the limit
What is wrong with my code?
#julia, there is one simple type in your code. Just remove the '*' at the end of the definition of 's'. And don't indent the recursion.
determinantRek<-function(X,k) {
if (dim(X)[1] == 1 && dim(X)[2] == 1)
return(X[1,1])
if (dim(X)[1] == 2 && dim(X)[2] == 2)
return(X[1,1]*X[2,2]-X[1,2]*X[2,1])
else
s = 0
for (i in 1:dim(X)[2]) {
s = s + X[k,i]*(-1)^(k+i)
determinantRek(X[-k,-i],k)
}
return(s)
}
I did this way and works just fine, although it is super slow, compared to the det function in base R
laplace_expansion <- function(mat){
det1 <- function(mat){
mat[1]*mat[4]-mat[2]*mat[3]
}
determinant <- 0
for(j in 1:ncol(mat)){
mat1 <- mat[-1,-j]
if(nrow(mat1) == 2){
determinant <- determinant+mat[1,j]*(-1)^(1+j)*det1(mat1)
}else{
val <- mat[1,j]*(-1)^(1+j)
if(val != 0){
determinant <- determinant+val*laplace_expansion(mat1)
}
}
}
return(determinant)
}
This is my approach, I think it's cleaner.
deter <- function(X) {
stopifnot(is.matrix(X))
stopifnot(identical(ncol(X), nrow(X)))
if (all(dim(X) == c(1, 1))) return(as.numeric(X))
i <- 1:nrow(X)
out <- purrr::map_dbl(i, function(i){
X[i, 1] * (-1)^(i + 1) * deter(X[-i, -1, drop = FALSE])
})
return(sum(out))
}
Thank you #ArtemSokolov and #MrFlick for pointing the problem cause, it was it. I also discovered that this code does not calculate properly the determinant of 2x2 matrix. After all it looks like that:
determinantRek<-function(X,k) {
if (dim(X)[1] == 1 && dim(X)[2] == 1)
return(X[1,1])
if (dim(X)[1] == 2 && dim(X)[2] == 2)
return(X[1,1]*X[2,2]-X[1,2]*X[2,1])
else
s = 0
for (i in 1:dim(X)[2]) {
s = s + X[k,i]*(-1)^(k+i)*
determinantRek(X[-k,-i],k)
}
return(s)
}
Debuging with browser() was also helpful :)