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"))
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