[R] Feed rle() output to hist()

Sarah Goslee sarah.goslee at gmail.com
Tue Mar 26 22:11:03 CET 2013


Do you want a histogram of the length distribution, or a barplot of
the actual lengths?

Either way,

myrle$lengths

will get it, if myrle is the output of rle().

?rle

tells you that:
     ‘rle()’ returns an object of class ‘"rle"’ which is a list with
     components:

 lengths: an integer vector containing the length of each run.

  values: a vector of the same length as ‘lengths’ with the
          corresponding values.


If you don't understand what list components are, you should certainly
read Introduction to R. Looking at the help is always a better place
to start than looking at the code, though the last line of the code
shows exactly the same thing.

Here's an example:

x <- c(rev(rep(6:10, 1:5)), 5, rep(6:10, 1:5))
myrle <- rle(x)

hist(myrle$lengths)
barplot(myrle$lengths)


Sarah


On Tue, Mar 26, 2013 at 5:02 PM, Newbie1234 <larry at riskengineer.com> wrote:
> I want to make a histogram from the lengths vector which is part of the
> output of rle.  But I don't know how to access that vector so that I use it
> as an argument of hist().  What argument must I use so that I use the
> lengths vector as an input to hist()?
>
> Example output is:
>
> Run Length Encoding
>   lengths: int [1:4] 1 2 3 3
>   values : num [1:4] -1 1 -1 1
>
> A printout of the function rle() may give some clues, however - not enough
> for me.  Here is the print out of rle()
>
>> rle
> function (x)
> {
>     if (!is.vector(x) && !is.list(x))
>         stop("'x' must be an atomic vector")
>     n <- length(x)
>     if (n == 0L)
>         return(structure(list(lengths = integer(), values = x),
>             class = "rle"))
>     y <- x[-1L] != x[-n]
>     i <- c(which(y | is.na(y)), n)
>     structure(list(lengths = diff(c(0L, i)), values = x[i]),
>         class = "rle")
> }
> <bytecode: 0x7fc7060a52d8>
> <environment: namespace:base>
>
>


--
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list