1

Im trying to store all the prime numbers in a vector into an object.

Q8.16 <-function(vector){ for(i in 1:length(vector)){ if (vector[i] == 2L || all(vector[i] %% 2L:ceiling(sqrt(vector[i])) != 0)){ prime1<-NULL prime1<-append(prime1,vector[i]) } } prime1 } sample1<-sample(1:1000 ,1000) Q8.16(sample1) 

The output I get from it is only one digit instead of a vector with all the prime numbers. Why is this happening?

4
  • emptyvector is never used, and return exits the function immediately when it finds the first prime number. Commented Apr 11, 2021 at 19:59
  • Would you please explain what is the purpose of this loop? So maybe I can rewrite it. Commented Apr 11, 2021 at 20:00
  • @pseudospin i removed those and i still only get one value Commented Apr 11, 2021 at 20:01
  • 1
    @AnoushiravanR The loop basically has to look for prime numbers in a vector with whole positive numbers. It then has to return all of those prime numbers. Is that clear? Commented Apr 11, 2021 at 20:03

1 Answer 1

2

If I'm understanding your intention correctly, it looks like the only change you need to make is move prime1<-NULL just before the for-loop. In your version of the code, you were resetting the list of primes every time you found a new one. The fixed version (with spacing tidied up) is below.

Q8.16 <- function(vector) { prime1 <- NULL # moved this outside the for-loop for (i in 1:length(vector)) { if (vector[i] == 2L || all(vector[i] %% 2L:ceiling(sqrt(vector[i])) != 0)) { prime1 <- append(prime1, vector[i]) } } prime1 } sample1 <- sample(1:1000, 1000) Q8.16(sample1) 

Testing it with sample1 <- 1:100 returns [1] 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 which looks correct to me.

Sign up to request clarification or add additional context in comments.

1 Comment

oh my i was so blind. Thank you for bringing that to my attention.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.