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.
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