# How to make a regression model for a relation looking like a step function ? Why can't I get an output for recursive partitioning done below?

I'm working on a dataset to describe the relationship between length and age of bluegill fish and the linear model based plot looks like this:

I hence tried using recursive partitioning algorithm as answered here by Matthew Drury.

I tried the following code:

df <- data.frame(x=length, y= age)
tree <- rpart(y ~ x, data=df)
summary(fish)

plot_tree <- function(tree, x, y) {
s <- seq(50, 200, by=1)
plot(x, y)
lines(s, predict(tree, data.frame(x=s)))
}
plot_tree(tree, age, length)


With this, I get the following output: That is,I don't get the joining curve.I really can't figure out what is wrong with not getting a line when all the code ran without an error.

1) Knowing why I can't get a line by 'lines' for this rpart would really help me.

2) If not, please suggest me any other method to fit a model for this data. Thanks in advance!

• Regarding the step function bit mentioned in the title, that seems to be related to isotonic regression. en.wikipedia.org/wiki/Isotonic_regression – not_bonferroni Jan 16 '17 at 18:42
• Thanks, seems relevant! I tried isotonic model using bivisio function in library(Iso) the R-code: y<-as.matrix(fish[c(1,2),]) biviso(y, w = NULL, eps = NULL, eps2 = 1e-9, ncycle = 50000, fatal = TRUE, warn = TRUE) I obtained matrix of the same dimensions as y containing the corresponding isotonic values. How do I construct the model from these isotonic values? Any help please? [,1] [,2] [1,] 1 64.5 [2,] 1 64.5 – Bharat Ram Ammu Jan 16 '17 at 19:15
• You have a discrete age variable, but the relationship between E(Age|Length) and Length is not actually a step function. (It's possible you may want your fitted model to return a discrete predicted age though, rather than an expected age; you should make that explicit, because the term regression usually suggests a model for the expected value) – Glen_b Jan 17 '17 at 0:48
• @BharatRamAmmu, you could also consider piecewise linear regression while supressing the slope, which would create a step function as your regression equation and is not restricted to being monotone, as in isotonic regression. – not_bonferroni Jan 17 '17 at 15:10
• @Glen_b that is a great insight, I will re-consider my model – Bharat Ram Ammu Jan 17 '17 at 18:24