Reputation: 13
I am trying to write a loop that performs year to year analysis on my data set. I am new to R, but in other programming languages, I would do something similar to data2$YEAR_RISK +1, but this doesn't seem to be working. My code is below:
for(i in 1:nrow(data2))
data2$Results[i] <-
ifelse(data2$Change[i] < 0, print(
paste(
"From", data2$YEAR_RISK [i], "to", data2$YEAR_RISK +1[i], data2$RESOURCE_UTILIZATION_BAND[i], "decreased by", data2$Change[i]
)
), ifelse(data2$Change[i] > 0 ,print(
paste(
"From", data2$YEAR_RISK[i], "to", data2$YEAR_RISK +1[i], data2$RESOURCE_UTILIZATION_BAND[i], "increased by", data2$Change[i]
)
),"0"))
The result I get is "From 2015 to 2015 0 decreased by -0.02" when I want it to say "From 2014 to 2015 0 decreased by -0.02". Any help is much appreciated.
Upvotes: 0
Views: 119
Reputation: 640
On of the many good thing with R is that most functions will work very well with vectors. In your case, there is no need of a for
loop, and you could just write:
data2$Results <- paste("From", data2$YEAR_RISK, "to", data2$YEAR_RISK + 1, data2$RESSOURCE_UTILIZATION_BAND, ifelse(data2$Change == 0, "0", ifelse(data2$Change < 0, "decreased by", "increased by"), data2$Change))
Upvotes: 1