0

I am practicing looping over the values that are found in a particular column (Z_SCORE). however I want to now append the result of each iteration into a data frame. Can I get some assistance on how I could go about to do that. The new data frame will be variables and the name of the column being comment. Any edits to my code are welcome.

variables$comment<-data.frame()

for (i in grade$Z_SCORE){
  if (i <= -0.5){
    print("good")
  } else if (i >=0.5){
    print("bad")
  }else
   print("neutral")
}

My desired output is a data frame with something like:

Comment
good
good
bad
neutral

I know I can do it using thee code below (A), however I want to learn how to use a for loop in r

A<-grades%>%
  mutate(comment = case_when(Z_SCORE <= -0.5 ~ "good",
                                 Z_SCORE >= 0.5 ~ "bad",
                                 T ~ "neutral"))
Julian
  • 6,586
  • 2
  • 9
  • 33
thole
  • 117
  • 6
  • `variables$comment[i] <-` will allocate something to the `i`th position of the `comment` column in the `variables` dataframe. This means that each iteration of the loop will insert into a different slot. This requires that you change your loop to a 1:n format, then extract the `i`th value from `Z_SCORE` instead of iterating over `Z_SCORE` directly. – Paul Stafford Allen Feb 23 '23 at 10:06
  • Thank you, if it will not be any trouble to you could you please write the comment in form of the code. It will assist me in trying to follow what you are saying. – thole Feb 23 '23 at 10:15

1 Answers1

0

Generally speaking, an approach like this would work:

# Prepare output
comments <- list(rep("", length(grade$Z_SCORE))

# then fill the list
for (i in seq_along(grade$Z_SCORE)){
  # if grade$Z_SCORE has 7 items, this loop will be run with i = 1, then 2, then 3... then 7.
  # we want to compare to the value of the i'th element of grade$Z_SCORE
  j <- grade$Z_SCORE[i]
  comments[i] <- if (j <= -0.5){
      "good"
    } else if (j >=0.5){
      "bad"
    } else {"neutral"}
}

# you can now add the filled list to a data frame if needed
Paul Stafford Allen
  • 1,840
  • 1
  • 5
  • 16
  • I have tried this attempt but now it returns an error ```Error in `[<-.data.frame`(`*tmp*`, i, value = "good") : replacement has 1 row, data has 0``` – thole Feb 23 '23 at 11:47
  • 1
    ah, you will need to pre-allocate your output. Personally I would make it a list - I'll amend the answer. – Paul Stafford Allen Feb 23 '23 at 12:52