recode {lazy.tools}R Documentation

Recode the Values of obj from "from" to "to".

Description

Recode the Values of obj from "from" to "to".

Usage

recode(
  obj,
  from = NULL,
  to = NULL,
  ft = NULL,
  method = 2,
  useNA = 0,
  debug = 0
)

Arguments

obj

a vector, matrix or list of those.

from

a vector of old values

to

a vector or new values

ft

the conversion table data frame

method

= 1 to use merge,
= 2 to use R style teble look-up using names attribute of a vector.

useNA

= 1 to mark out-of-range elements

debug

= 1 to print intermediate result.

Details

When ft is not given, cbind(from,to) makes the conversion table ft.
ft has priority over from and to.

The core of this function is:

If method==1
New <- merge( cbind(from,to), data.frame(from=c(obj)) , by="from", sort=FALSE, all.y=TRUE )
If method==2
names(to) <- from; New <- to[as.character(c(obj))]

Method 2 is faster than method 1.

If the conversion table is not large enough, if method=2 and useNA=1, out-of-range elements will be set to NAs, otherwise, the original values will not be changed.

When the types of obj and from are different, they will be converted to character.

lazy.tools::new_name will be deprecated.

Value

A matrix or vector depending on the obj. When obj is a list, a list will be returned.

Examples

n <- 10
n1 <- n-2
obj <- cbind( letters[1:n], rev( letters[1:n] ) )
obj[1,1] <- NA; obj[3,2] <- NA
rownames(obj) <- paste("RR",1:n,sep="")
colnames(obj) <- paste("CC",1:ncol(obj),sep="")
from <- letters[1:n1]
to <- LETTERS[1:n1]
# to <- 1:n1
res <- recode( obj, from, to )
Print(obj,res,from,to)
res2 <- recode( obj, from, to, useNA=1 )
Print(obj,res2,from,to)


n=10
n1=n-2
obj=cbind( 1:n, n:1 )
rownames(obj)=paste("RR",1:n,sep="")
colnames(obj)=paste("CC",1:ncol(obj),sep="")
from=1:n1
to=from^2
res=recode( obj, from, to, method=2 )
Print(obj,res, from, to)


n <- 10
n1 <- n-2
obj <- cbind( 1:n, n:1 )        # This is numeric.
rownames(obj) <- paste("RR",1:n,sep="")
colnames(obj) <- paste("CC",1:ncol(obj),sep="")
from <- as.character(1:n1)      # This is character.
to <- LETTERS[1:n1]
res <- recode( obj, from, to )
Print(obj,res, from, to)


[Package lazy.tools version 0.1.6 ]