[R-gregmisc-users] SF.net SVN: r-gregmisc:[1506] trunk/gdata
Brought to you by:
warnes
From: <wa...@us...> - 2011-09-20 18:07:13
|
Revision: 1506 http://r-gregmisc.svn.sourceforge.net/r-gregmisc/?rev=1506&view=rev Author: warnes Date: 2011-09-20 18:07:07 +0000 (Tue, 20 Sep 2011) Log Message: ----------- Add case() function, a vector equivalent of the switch() function Added Paths: ----------- trunk/gdata/R/case.R trunk/gdata/man/case.Rd Added: trunk/gdata/R/case.R =================================================================== --- trunk/gdata/R/case.R (rev 0) +++ trunk/gdata/R/case.R 2011-09-20 18:07:07 UTC (rev 1506) @@ -0,0 +1,16 @@ +case <- function(x, ..., default=NA) +{ + magic <- "....default...." + alternatives <- c(...,"....default...."=magic) + + x <- as.character(x) + retval <- factor( + x, + levels=alternatives, + labels=names(alternatives) + ) + levels(retval)[length(alternatives)] <- as.character(default) + retval[is.na(retval) & !is.na(x)] <- default + + retval +} Added: trunk/gdata/man/case.Rd =================================================================== --- trunk/gdata/man/case.Rd (rev 0) +++ trunk/gdata/man/case.Rd 2011-09-20 18:07:07 UTC (rev 1506) @@ -0,0 +1,37 @@ +\name{case} +\alias{case} +\title{Map elements of a vector according to the provided 'cases'} +\description{ + Map elements of a vector according to the provided 'cases'. This + function is useful for mapping discrete values to factor labels and + is the vector equivalent to the \code{switch} function. +} +\usage{ +case(x, ..., default = NA) +} +\arguments{ + \item{x}{Vector to be converted} + \item{\dots}{Map of alternatives, specified as "name"=value} + \item{default}{Value to be assigned to elements of \code{x} not + matching any of the alternatives. Defaults to \code{NA}.} +} +\details{ + This function is to \code{switch} what \code{ifelse} is to \code{if}, + and is a convenience wrapper for \code{factor}. +} +\value{ + A factor variables with each element of \code{x} mapped into the + corresponding level of specified in the mapping. +} +\author{Gregory R. Warnes \email{gr...@wa...}} +\seealso{\code{factor}, \code{switch}, \code{ifelse}} +\examples{ +## default = NA +case( c(1,1,4,3), "a"=1, "b"=2, "c"=3) + +## default = "foo" +case( c(1,1,4,3), "a"=1, "b"=2, "c"=3, default="foo" ) + + +} +\keyword{ manip } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |