Isaac - 1 year ago 38

R Question

In **R**, how can I create dimname names to an already existing tables?

Now I have a table as follow.

I would like to name each dimension by using dnn option

of table, such as

`obs=as.table(obs,dnn=c("Math","Statistics"))`

But the dimname names are not correctly named.

How do I create dimname names to a existing table?

What I would like to know is how to create the names for each variable in the contingency table. That is, for example, the first dimension, I would name the variable "Math" which has two rows "dislike" and "like". And then, for the second dimension, I would name the variable "Statistics" which has two columns "dislike" and "like"

So I would like the table to look as follow:

Answer Source

Here is a toy example:

```
obs <- table(gl(2,2), gl(2,2))
# 1 2
# 1 2 0
# 2 0 2
dimnames(obs) <- list(c("Math","Statistics"), c("Math","Statistics"))
# Math Statistics
#Math 2 0
#Statistics 0 2
```

You can't use `as.table`

to achieve what you want, because:

```
> as.table.default
function (x, ...)
{
if (is.table(x))
return(x)
....
```

Your `obs`

is readily a table, so `as.table`

does nothing but return it straight away.

Maybe I should have explained this better. What I would like to know is how to create the names for each variable in the contingency table. That is, for example, the first dimension, I would name the variable "Math" which has two rows "dislike" and "like". And then, for the second dimension, I would name the variable "Statistics" which has two columns "dislike" and "like".

Then you need a named list:

```
dimnames(obs) <- list(Math = c("dislike", "like"), Statistics = c("dislike", "like"))
# Statistics
#Math dislike like
# dislike 2 0
# like 0 2
```