Description Usage Arguments Details Value See Also Examples
recode
substitutes old values of a factor or a numeric
vector by new ones, just like the recoding facilities in some
commercial statistical packages.
1 2 3 4 5 6 |
x |
An object |
... |
One or more assignment expressions, each
of the form Each In case of the method for If the |
otherwise |
a character string or some other value
that the result may obtain. If equal to |
recode
relies on the lazy evaluation mechanism of R:
Arguments are not evaluated until required by the function they are given to.
recode
does not cause arguments that appear in ...
to be evaluated.
Instead, recode
parses the ...
arguments. Therefore, although
expressions like 1 <- 1:4
would cause an error action, if evaluated
at any place elsewhere in R, they will not cause an error action,
if given to recode
as an argument. However, a call of the
form recode(x,1=1:4)
, would be a syntax error.
If John Fox' package "car" is installed, recode
will also be callable
with the syntax of the recode
function of that package.
A numerical vector, factor or an item
object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | x <- as.item(sample(1:6,20,replace=TRUE),
labels=c( a=1,
b=2,
c=3,
d=4,
e=5,
f=6))
print(x)
# A recoded version of x is returned
# containing the values 1, 2, 3, which are
# labelled as "A", "B", "C".
recode(x,
A = 1 <- range(min,2),
B = 2 <- 3:4,
C = 3 <- range(5,max), # this last comma is ignored
)
# This causes an error action: the sets
# of original values overlap.
try(recode(x,
A = 1 <- range(min,2),
B = 2 <- 2:4,
C = 3 <- range(5,max)
))
recode(x,
A = 1 <- range(min,2),
B = 2 <- 3:4,
C = 3 <- range(5,6),
D = 4 <- 7
)
# This results in an all-missing vector:
recode(x,
D = 4 <- 7,
E = 5 <- 8
)
f <- as.factor(x)
x <- as.integer(x)
recode(x,
1 <- range(min,2),
2 <- 3:4,
3 <- range(5,max)
)
# This causes another error action:
# the third argument is an invalid
# expression for a recoding.
try(recode(x,
1 <- range(min,2),
3:4,
3 <- range(5,max)
))
# The new values are character strings,
# therefore a factor is returned.
recode(x,
"a" <- range(min,2),
"b" <- 3:4,
"c" <- range(5,6)
)
recode(x,
1 <- 1:3,
2 <- 4:6
)
recode(x,
4 <- 7,
5 <- 8,
otherwise = "copy"
)
recode(f,
"A" <- c("a","b"),
"B" <- c("c","d"),
otherwise="copy"
)
recode(f,
"A" <- c("a","b"),
"B" <- c("c","d"),
otherwise="C"
)
recode(f,
"A" <- c("a","b"),
"B" <- c("c","d")
)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.