Renaming rows and columns in R
Question
I'm running the following script:
cause = c(1, 1, 1, 1, 1, 2, 1, 2, 2, 2, 2);
time = c(1, 1, 2, 3, 3, 2, 2, 1, 1, 2, 2);
table(cause, time)
And I get the following:
time
cause 1 2 3
1 2 2 2
2 2 3 0
What I want is this:
time
cause 1 2 3
Maltreat 2 2 2
Non-Maltr 2 3 0
So, my question is: how do you rename the rows of a table in R?
In the same vein, how would you rename the columns of that table?
Solution
One way to do it is to use factors or lists of strings instead of indexes. So:
cause1 <- c("Maltreat", "Non-malt")[cause]
> print(cause1)
[1] "Maltreat" "Maltreat" "Maltreat" "Maltreat" "Maltreat" "Non-malt"
[7] "Maltreat" "Non-malt" "Non-malt" "Non-malt" "Non-malt"
> table(cause1, time)
time
cause1 1 2 3
Maltreat 2 2 2
Non-malt 2 3 0
And, in case you're worried about memory or speed, R is pretty good at representing this sort of thing efficiently internally, with only a single instance of the whole string stored, and the rest done with indexes.
Incidentally, you'll be happier in the long run with data frames:
> df <- data.frame(cause=as.factor(c("Maltreat", "Non-malt")[cause]), time=time)
> summary(df)
cause time
Maltreat:6 Min. :1.000
Non-malt:5 1st Qu.:1.000
Median :2.000
Mean :1.818
3rd Qu.:2.000
Max. :3.000
> table(df)
time
cause 1 2 3
Maltreat 2 2 2
Non-malt 2 3 0
OTHER TIPS
There are two easy ways to do this:
z <- table(cause, time)
Use the colnames/rownames functions:
> colnames(z)
[1] "1" "2" "3"
> rownames(z)
[1] "1" "2"
Or use dimnames:
> dimnames(z)
$cause
[1] "1" "2"
$time
[1] "1" "2" "3"
> dimnames(z)$cause
[1] "1" "2"
In any case, choose your names as a vector and assign them:
> dimnames(z)$cause <- c("Maltreat","Non-malt")
> z
time
cause 1 2 3
Maltreat 2 2 2
Non-malt 2 3 0
Don't forget plyr's wonderful "revalue" and "rename" command!