[R] inverse table

Leonardo Fontenelle
Wed, 15 Jun 2016 16:49:35 -0000

Em Qua 15 jun. 2016, ?s 13:10, Patrizio Frederic
escreveu:
> Dear R-users,
> I've a problem that puzzle me
>
> suppose I have a two way contigency  table
>
> a <- sample(al <- letters[1:10],100,T)
> b <- sample(bl <- LETTERS[1:5],100,T)
> ab <- cbind(a,b)
>
> ddd <- (xtabs(data = ab))
> ddd <- as.matrix(ddd)
>
> the question is: how do I reverse the code, thus how do I get raw data
> (object ab) from ddd?

I believe packages reshape and reshape2 could help, although I don't use
them.

a <- sample(al <- letters[1:10],100,T)
b <- sample(bl <- LETTERS[1:5],100,T)
ab <- cbind(a,b)
ddd <- (xtabs(data = ab))
ddd <- as.matrix(ddd)

df <- expand.grid(dimnames(ddd), stringsAsFactors = FALSE)
df$freq <- as.vector(ddd)
ab2 <- as.matrix(df[rep(seq.int(nrow(df)), df$freq), 1:2])
all.equal(ab2[order(ab2[, c("a", "b")])],
          ab[order(ab[, c("a", "b")])])

Hope that helps,

Leonardo Ferreira Fontenelle