I have a for loop that works on its own, but when I turn it into a function I do not get the output. The for loop populates a new column of a dataframe based on date ranges. I put in a data frame x and I want a new column with the new variable ,ay, populated.
Here is a data frame:
score <- c(86, 95, 48, 99)
date <- ymd(c('2013-07-12','2014-08-18', '2015-05-24', '2016-08-02'))
test <- data.frame(score,date)
Here is the for loop:
for (i in seq_along(x)) {
if (year(x$date[i]) == 2012 & month(x$date[i]) %in% c(8:12) | year(x$date[i]) == 2013 & month(x$date[i]) %in% c(1:7)) {
x$ay[i] <- 1213
}
else if (year(x$date[i]) == 2013 & month(x$date[i]) %in% c(8:12) | year(x$date[i]) == 2014 & month(x$date[i]) %in% c(1:7)) {
x$ay[i] <- 1314
}
}
However when I try to turn this for loop into a function it does not populate the new variable. I am missing something fundamental here. Do I need some sort of return?
my_fun <- function(x) { for (i in seq_along(x)) {
if (year(x$date[i]) == 2012 & month(x$date[i]) %in% c(8:12) | year(x$date[i]) == 2013 & month(x$date[i]) %in% c(1:7)) {
x$ay[i] <- 1213
}
else if (year(x$date[i]) == 2013 & month(x$date[i]) %in% c(8:12) | year(x$date[i]) == 2014 & month(x$date[i]) %in% c(1:7)) {
x$ay[i] <- 1314
}
}
return(x)
}