user5243421 user5243421 - 2 months ago 7
R Question

Renaming rows and columns in R

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?

Answer

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
Comments