1

Let's say I have a frequency table:

t = matrix(c(20,10,5,15), ncol=2, dimnames=list(c("yes","no"), c("yes","no")))
t
    yes no
yes  20  5
no   10 15

I want to convert the frequency table back to raw data. My code is (which is not working):

a = rep(c("yes","no"), colSums(t(t)))
b = rep(c("yes","no"), colSums(t))

table(a,b)
        b
a     no yes
  no  20   5
  yes  0  25

Can someone tell me what is wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
wen
  • 1,875
  • 4
  • 26
  • 43
  • It's not a good idea to call a matrix `t` because `t` is a function that is mainly used for matrices. Something like `t(t) %*% t` isn't very readable. – Roland Jun 06 '14 at 07:25

2 Answers2

2
mat <- matrix(c(20,10,5,15), ncol=2, dimnames=list(c("yes","no"), c("yes","no")))

a <- rep(rep(c("yes", "no"), 2), c(mat))
b <- rep(c("yes", "no"), colSums(mat))
a <- factor(a, levels=c("yes", "no"))
b <- factor(b, levels=c("yes", "no"))


table(a, b)
     b
a     yes no
  yes  20  5
  no   10 15
Roland
  • 127,288
  • 10
  • 191
  • 288
0

I think you want to use melt from reshape2:

test = matrix(c(20,10,5,15), ncol=2, dimnames=list(c("yes","no"), c("yes","no")))

test
#    yes no
#yes  20  5
#no   10 15

library(reshape2)

melt(test)
#  Var1 Var2 value
#1  yes  yes    20
#2   no  yes    10
#3  yes   no     5
#4   no   no    15
talat
  • 68,970
  • 21
  • 126
  • 157
  • what if we want 20 rows for "yes" "yes", 10 rows of "no" "yes" ...? – useR Jun 06 '14 at 07:25
  • @useR check out https://stackoverflow.com/questions/2894775/replicate-each-row-of-data-frame-and-specify-the-number-of-replications-for-each – Joe Apr 14 '19 at 23:28