adv-r icon indicating copy to clipboard operation
adv-r copied to clipboard

Quiz/Answer 4.6 (5) doubts

Open CorradoLanera opened this issue 4 years ago • 1 comments

In the quiz: traditionally, I think to categorical variables like factors. I have supposed you asked how to change factors’ labels using named character vectors (and subsetting).

Something like

f <- factor(letters)

# suppose recoder is not correctly ordered
recoder <- sample(setNames(rev(letters), letters))

levels(f) <- recoder[levels(f)]

But your answer make me think I’m wrong

In the answer: where is the named character vector?

CorradoLanera avatar Feb 28 '20 00:02 CorradoLanera

All confusion would disappear by changing "relabel categorical variables" to "recode character vectors" in the question:

  1. How can you use a named vector to relabel categorical variables?

It fits the answer, which depicts the re-coding of a character vector to a numeric vector:

A named character vector can act as a simple lookup table: c(x = 1, y = 2, z = 3)[c("y", "z", "x")]

Using "character" over "categorical" is not overly specific, because character vectors really are the only "categorical" vectors you can recode like this. You can't do it with factors (which are indeed categorical as @CorradoLanera points out) since they're converted to integer:

c(x = 1, y = 2, z = 3)[factor(c("y", "z"))]
# Result:
# x y 
# 1 2

NikKrieger avatar Mar 26 '20 14:03 NikKrieger