1
votes

I want to style the output of table(). Suppose I have the following:

dat$a <- c(1,2,3,4,4,3,4,2,2,2)
dat$b <- c(1,2,3,4,1,2,4,3,2,2)
table(dat$a,dat$b)

    1   2   3   4
1  50   0   0   0
2   0 150  50   0
3   0  50  50   0
4  50   0   0 100

There are two problems with this. First, it doesn't give me the correct frequencies. Additionally, it has no row or column labels. I found this, and the table works for both frequency counts and axis labels. Is there an issue because this way subsets from a data frame? I would appreciate any tips on both fixing the frequency counts and adding style to the table.

1
How many nrow(dat) do you have?Khashaa
The margins are labeled if you use with(dat,table(a,b)) or table(a=dat$a,b=dat$b) or table(dat[,c("a","b")]). I don't know why your frequencies are off. For the example you give, the frequencies should be only 1/50th of the counts you're showing.Frank
dat is likely a 500 row data frame, which has been filled via recycling.Chris
I did have 500 rows, and I ran it in my program and it gave me the correct frequencies (so that's not an issue anymore). I tried doing table(dat[,c("a","b")]) but still didn't get any labels. If it makes a difference, I'm running this in shiny using renderTable.Kira Tebbe
I reformatted my question and posted it here.Kira Tebbe

1 Answers

4
votes

The only problem is the way that you are inputting arguments to table. To get the desired output (with labels), use the data frame as argument, not 2 vectors (the columns). If you have a larger data frame, use only the subset that you want.

 a <- c(1,2,3,4,4,3,4,2,2,2)
 b <- c(1,2,3,4,1,2,4,3,2,2)
 dat <- data.frame(a,b)
 table(dat)

Gives me the output:

   b
a   1 2 3 4
  1 1 0 0 0
  2 0 3 1 0
  3 0 1 1 0
  4 1 0 0 2

It shouldn't give the wrong frequencies, even with your approach. You could try restarting your R session to check this.