I hope someone can help me figure out how to write an if-else statement to work with my dataset. I have data on the growth rate of trees by year. I need to calculate whether the growth rate has fallen by> 50% from year to year. I'm having trouble using the ifelse statement to calculate my final field. I'm relatively new to R, so my code is probably not very efficient, but here is an example of what I still have: For an example dataset
test<-data.frame(year=c("1990","1991","1992","1993"),value=c(50,25,20,5)) year value 1 1990 50 2 1991 25 3 1992 20 4 1993 5
Then I calculate the difference between the growth of the current year and the previous year ("value"):
test[-1,"diff"]<-test[-1,"value"]-test[-nrow(test),"value"] year value diff 1 1990 50 NA 2 1991 25 -25 3 1992 20 -5 4 1993 5 -15
and then calculate that there will be 50% growth of each year:
test$chg<-test$value * 0.5 year value diff chg 1 1990 50 NA 25.0 2 1991 25 -25 12.5 3 1992 20 -5 10.0 4 1993 5 -15 2.5
Then I try to use the ifelse operator to calculate the โcoolโ field, which will be โ1โ when the decline from one year to the next is more than 50%. This is the code I'm trying to use, but I'm not sure how to refer to the "chg" field from the previous year correctly, because I get an error message (copied below):
test$abrupt<-ifelse(test$diff<0 && abs(test$diff)>=test[-nrow(test),"chg"],1,0) Warning message: In abs(test$diff) >= test[-nrow(test), "chg"] : longer object length is not a multiple of shorter object length > test year value diff chg abrupt 1 1990 50 NA 25.0 NA 2 1991 25 -25 12.5 NA 3 1992 20 -5 10.0 NA 4 1993 5 -15 2.5 NA
A test of a similar ifelse statement worked when I just assigned multiple numbers, but I'm not sure how to get this to work in the context of a datframe. Here is an example that it only works with a few values:
prevyear<-50 curryear<-25 chg<-prevyear*0.5 > chg [1] 25 > diff<-curryear-prevyear > diff [1] -25 > abrupt<-ifelse(diff<0 && abs(diff)>= chg,1,0) > abrupt [1] 1
If anyone can help me figure out how to apply a similar ifelse statement to my database, I would really appreciate it! Thank you for any help you can provide.
Thank you Katie