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?
To rename a column in R you can use the rename() function from dplyr. For example, if you want to rename the column “A” to “B”, again, you can run the following code: rename(dataframe, B = A) .
A data frame's rows can be accessed using rownames() method in the R programming language. We can specify the new row names using a vector of numerical or strings and assign it back to the rownames() method. The data frame is then modified reflecting the new row names.
rename() function in R Language is used to rename the column names of a data frame, based on the older names.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With