[R] Breakdown a number [Broadcast]
Liaw, Andy
andy_liaw at merck.com
Thu Apr 20 02:18:55 CEST 2006
I meant to send this to R-help, but it went to Gabor instead...
This is my shot at it using diff(), assuming breaks is in non-decreasing
order:
chop <- function(x, breaks) {
s <- sign(x - breaks)
if (x <= breaks[1]) {
ans <- x
} else {
numPieces <- sum(s == 1)
ans <- diff(c(0, breaks[1:numPieces], x))
}
ans
}
Some tests:
> chop(1200, c(250, 800))
[1] 250 550 400
> chop(800, c(250, 800))
[1] 250 550
> chop(100, c(250, 800))
[1] 100
> chop(600, c(250, 800))
[1] 250 350
Andy
From: Paul Roebuck
>
> On Wed, 19 Apr 2006, Gabor Grothendieck wrote:
>
> > On 4/19/06, Paul Roebuck <roebuck at mdanderson.org> wrote:
> >
> > > Isn't there a builtin method for doing this and, if so,
> what is it
> > > called?
> > >
> > > breakdown <- function(whole) {
> > > breaks <- c(250, 800)
> > > pieces <- integer(length(breaks) + 1)
> > > if (whole > breaks[2]) {
> > > pieces[3] <- whole - breaks[2]
> > > whole <- breaks[2]
> > > }
> > > if (whole > breaks[1]) {
> > > pieces[2] <- whole - breaks[1]
> > > whole <- breaks[1]
> > > }
> > > pieces[1] <- whole
> > >
> > > return(pieces)
> > > }
> > >
> > > breakdown(1200) # 250 550 400
> >
> > Maybe you could discuss in words what you want but perhaps you are
> > looking for diff:
>
> That was rather my problem searching for my answer as I
> was unsure what this was called. I was searching for
> 'bins' or 'breaks' (like in hist method but not for
> plotting) and leading nowhere fast. Alas, I thought
> sample code would go further than my description.
>
>
> > > bp <- c(0, 250, 800, 1200)
> > > diff(bp)
> > [1] 250 550 400
>
> Don't think diff method is going to work either, at
> least in cases where the 'whole' is less than greatest
> 'break'.
>
> > breakdown2 <- function(x, breaks = c(250, 800)) {
> diff(c(0, breaks, x))
> }
> > breakdown(10) # 10 0 0
> > breakdown2(10) # 250 550 -790
> >
> > breakdown(400) # 250 150 0
> > breakdown2(400) # 250 550 -400
>
>
> ----------------------------------------------------------
> SIGSIG -- signature too long (core dumped)
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
>
More information about the R-help
mailing list