[R] How to call a value labels attribute?

Richard M. Heiberger rmh at temple.edu
Mon Jun 5 16:01:34 CEST 2006


Aha!  Thank you for the more detailed example.

My solution for that situation is an attribute "position" and function
as.position().  I use this in my book

                Statistical Analysis and Data Display
                Richard M. Heiberger and Burt Holland

The online files for the book are available at
                http://springeronline.com/0-387-40270-5



For this example, you need the function as.position() included in this
email.


### example ########
x <- ordered(c(1,2,3,2,4,3,1,2,4,3,2,1,3),
             labels=c("small", "medium", "large", "very.large"))
x
attr(x, "position") <- c(1,2,4,8)
x
as.position(x)

y <- rnorm(length(x))
y

xyplot(y ~ x)
source("~/h2/library/code/as.position.s")
xyplot(y ~ as.position(x))
xyplot(y ~ as.position(x),
       scale=list(x=list(at=attr(x,"position"), labels=levels(x))))
xyplot(y ~ as.position(x),
       scale=list(x=list(at=attr(x,"position"), labels=levels(x))),
       xlab="x")
### end example ########



### as.position.s #########
as.position <- function(x) {
  if (is.numeric(x))
    x
  else {
    if (!is.factor(x)) stop("x must be either numeric or factor.")

    if (!is.null(attr(x, "position")))
      x <- attr(x, "position")[x]
    else {
      lev.x <- levels(x)
      if (inherits(x, "ordered")) {
        on.exit(options(old.warn))
        old.warn <- options(warn=-1)
        if (!any(is.na(as.numeric(lev.x))))
          x <- as.numeric(lev.x)[x]
        else
          x <- as.numeric(ordered(lev.x, lev.x))[x]
      }
      else
        x <- as.numeric(x)
    }
  }
  x
}


## tmp <- ordered(c("c","b","f","f","c","b"), c("c","b","f"))
## as.numeric(tmp)
## as.position(tmp)
## 
## tmp <- factor(c("c","b","f","f","c","b"))
## as.numeric(tmp)
## as.position(tmp)
## 
## tmp <- factor(c(1,3,5,3,5,1))
## as.numeric(tmp)
## as.position(tmp)
## 
## tmp <- ordered(c(1,3,5,3,5,1))
## as.numeric(tmp)
## as.position(tmp)
## 
## tmp <- c(1,3,5,3,5,1)
## as.numeric(tmp)
## as.position(tmp)

### end as.position.s #########



More information about the R-help mailing list