For loop prints first result everywhere

Hi there, newby here.

I am trying to run a for loop to print the results in a new column. I have a data frame as so:

home / away / result
2 / 2 / NA
1 / 3 / NA

ect. The code I am using is:

for (i in 1:nrow(df))

{
  
  if (df[i, ] == df[i, ]){
    df$Result <- ("Draw")
  } else if (df[i, ] < df[i, ]){
    df$Result <- ("Away")
  } else {
    df$Result <- ("Home")
  }

}

I am trying to add the result to the last column, however what is happening is my loop is taking the result from the first row (which is a draw) and adding it to every entry in the last column. How can I get by this? any help would be greatly appreciated.

Thank you

a handcrafted loop is likely not the most elegant solution to your problem though understanding what is happening will help you in your R programming so, I'm happy to give you a simple example that you can consider.
What I want to emphasise is the difference of control whether you pick a particular element from a vector, or the vector as a whole.


#starting
(df1 <- data.frame(a = 1:2))

# setting everything in the column to something
df1$a <- "x"
df1

#setting only the 2nd entry of the column to something
df1$a[2] <-"y2"
df1
1 Like

Thank you, I managed to solve it with the following edits

for (i in 1:nrow(df))

{
  
  if (df[i,1] == df[i,2]){
    df$Result[i] <- ("Draw")
  } else if (df[i,1] < df[i,2]){
    df$Result[i] <- ("Away")
  } else {
    df$Result[i]<- ("Home")
  }

}

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.