読者です 読者をやめる 読者になる 読者になる

Recoding a factor variable in a data.frame by the levels() function

When you want to change the coding of a factor variable in R, you can use the levels() function.

Recoding z as 1 = A, 2-6 = B, 7 = C

d <- data.frame(z = gl(7, 1, 14))
d$zc <- factor(d$z)
levels(d$zc) <- list(A = 1, B = 2:6, C = 7)
d
Result
> levels(d$zc) <- list(A = 1, B = 2:6, C = 7)
> d
   z zc
1  1  A
2  2  B
3  3  B
4  4  B
5  5  B
6  6  B
7  7  C
8  1  A
9  2  B
10 3  B
11 4  B
12 5  B
13 6  B
14 7  C

Recoding z as 1 = "1", 2-6 = "2-6", 7 = "7"

levels(d$zc) <- list("1" = 1, "2-6" = 2:6, "7" = 7)
d
Result
> levels(d$zc) <- list("1" = 1, "2-6" = 2:6, "7" = 7)
> d
   z  zc
1  1   1
2  2 2-6
3  3 2-6
4  4 2-6
5  5 2-6
6  6 2-6
7  7   7
8  1   1
9  2 2-6
10 3 2-6
11 4 2-6
12 5 2-6
13 6 2-6
14 7   7