SpinningAtInfinity SpinningAtInfinity - 1 month ago 15
R Question

The error `Error: unexpected '}' in "}"`

I have a code

Eratosthenes <- function(n) {
if (n >= 2) {
sieve <- seq(2,n)
primes <- c()
for (i in seq(2,n)) {
if (any(sieve == i)) {
primes <- c(primes, i)
sieve <- c(sieve[(sieve %% i) ! = 0], i)
}
}
return(primes)
} else {
stop("Input value of n should be at least 2.")
}
}


with the error
Error: unexpected '}' in "}"
. However, everything seems perfect with
}
, but I don't what wrong. Could anyone be able to tell me where is my mistake?

Answer

The problem appears to be here: sieve <- c(sieve[(sieve %% i) ! = 0], i). I'm assuming that you want "is not equal to", so should be sieve <- c(sieve[(sieve %% i) != 0], i).

Here's the formatted code that works for me:

Eratosthenes <- function(n) {
  if (n >= 2) {
    sieve <- seq(2,n)
    primes <- c() 
    for (i in seq(2,n)) {
      if (any(sieve == i)) {
        primes <- c(primes, i)
        sieve <- c(sieve[(sieve %% i) != 0], i)
      }
    }
    return(primes)
  } else {
    stop("Input value of n should be at least 2.")
  }
}