0

I'm trying to make a table that evaluates two variables, like the one below:

  Diabetes No_Diabetes
1        0          12
2        5         234
3        7         182
4        3          57

By using table(x), I can get these frequencies for each individual column (in this example, Diabetes or No_Diabetes):

table(data$bmi_cat[DIABETES==0])

  1   2   3   4 
 12 234 182  57 

table(data$bmi_cat[DIABETES==1])

2 3 4 
5 7 3 

but because 1 = 0 in this example, when I try to put the two tables into one data frame, I receive an error message that states they cannot be combined because they are different lengths.

I succumbed to using for loops to make the original data frame above, but there has to be an easier way than writing 8 separate loops when "table" does this so efficiently. Any suggestions on how to combine the two tables, perhaps by finding a way to display 1 = 0 in the second table? Thanks!!!

Jem94
  • 3
  • 1
  • provide some data please. `with(data, table(bmi_cat, DIABETES))` would be a guess. not just one loop but EIGHT loops? really? how.. why?.. – rawr Jan 30 '15 at 22:16
  • Without data it's hard to say what's going on here, please read up on how to make a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Shambho Jan 31 '15 at 00:09

1 Answers1

0

In principle, you could just run the following piece to get your table:

table(data$bmi_cat,DIABETES)

Although it's difficult to solve without data, it seems the DIABETES is a binary vector. So here is an attempt to reverse engineer the problem from what you shared:

temp <- read.table(text="Diabetes No_Diabetes
0          12
5         234
7         182
3          57",header=TRUE)

temp

So lets create the two variables that you are using.

bmi_cat <- rep(1:4,apply(temp,1,sum))

DIABETES <- rep(rep(c(0,1),4),c(t(temp)))

Lets regenerate the tables you had:

table(bmi_cat[DIABETES==0])
table(bmi_cat[DIABETES==1])

Seems like we have set up the data suitably, now lets combine it in a data.frame, and run table on that:

data <- data.frame(bmi_cat,DIABETES)
table(data)

You actually don't need a data frame here, just following will do:

table(bmi_cat,DIABETES)
Shambho
  • 3,250
  • 1
  • 24
  • 37