Reputation: 133
I'm using the strucchange package in order to determine where my curve model segments.
My code looks like this:
l.fit <- loess(data$y~data$x)
px <- predict(l.fit,newdata=data$x)
bp <- breakpoints(px~1)
Now, the output of bp:
Optimal 6-segment partition:
Call:
breakpoints.formula(formula = px ~ 1)
Breakpoints at observation number:
161 254 347 440 533
Corresponding to breakdates:
0.2571885 0.4057508 0.5543131 0.7028754 0.8514377
The breakdates are kind of useless, as my x scale goes from 1 to 700 or so. But the breakpoints themselves are exactly what I want, specifically the last one, 533.
If i type:
bp[1]
I get:
$breakpoints
[1] 161 254 347 440 533
but if I try to assign bp[1]
to a new vector, I get nothing. Is there anyway I can isolate the last breakpoint, i.e. 533, and assign it to a variable so I can plot a vertical line at the breakpoint? I need to do this for a couple hundred datasets, so being able to isolate the breakpoints would be really useful.
Thanks!
Upvotes: 1
Views: 619
Reputation: 263481
I cannot tell whether you are so new at R that you think that the fact that executing this code should produce any console output:
vec <- bp[1]
What happens if you now type:
vec
You should be using either bp[["breakpoints"]][5] or bp$breakpoints[5] to get the last breakpoint. You would then want to use it as an index into data$x :
data$x[ bp$breakpoints[5] ]
If you are doing this "programmatically" it might be safer to use the [["quoted-name"]] version of access, since the $ version has some under-appreciated gotcha's.
Upvotes: 0
Reputation: 66874
[
extraction doesn't drop to the simpliest form, so it remains a list. Use [[
or $
extraction instead to get a numeric vector.
bps <- bp[[1]]
or
bps <- bp$breakpoints
To get the last one, you would need to either count its length and select the last one, or reverse it and select the first:
bps[length(bps)]
or
rev(bps)[1]
Upvotes: 4