jeudi 24 septembre 2020

Trying to create a for loop with nested if statements inside

Alright so I'm trying to do an assignment and I'm getting errors back but I'm not sure why. Here's the question, I'll break it up as I go.

Given the following code, x <- rnorm(10) Do the following.

(1) create a count vector named "count" of four elements and set each to 0 using the rep function.

So for this part I did

count <- c(1, 2, 3, 4)
rep(count, each=0)

I think this is correct? I don't know what it means by setting each to zero but after some looking around through R's help, I think this is how rep is set up. Correct me if I'm wrong.

(2) using a for loop to process each value in the vector x, count how many times each of the following values occur in the vector x using an if statement. a. "value is between -1 and 1 inclusive" b. "value is between -2 and 2 inclusive, but not between -1 and 1", c. "value is between -3 and 3 inclusive, but not between -2 and -2", or d. "value is greater than 3 or less than -3".

This is where I'm running into errors. Here's what I've got so far, code-wise

for (i in x) {
  if (i >= -1 & i <= 1) print("a") else 
    if (-2 =< i < -1 & 1 < i <= 2) print("b") else
      if (-3 =< i < -2 & 2 < i <= 3) print ("c")

When I tried this out, it says "error, unexpected '}' in " }" Which I have no idea what that means. I was going to keep going with this code and do else if, with the next set of requirements and so on. But obviously something is wrong and I can't figure out what. When I just had the first part (ending after print "a") it worked just fine. What changed?

(3) print each of the four counts in the count vector using a while loop.

I just straight up don't know what this means.


Anyway, I'm really new to R and programming in general, and I feel as if my professor has not really gone this in-depth on this sort of problem, so I'm very lost and turning to the internet for help.

Aucun commentaire:

Enregistrer un commentaire