0

I am trying to efficiently build a data frame that could represent the source of a frequency table in R.

Easy example:

A <- data.frame(Age=c(20,60,20,60), Health=c("Good","Good","Bad","Bad"), Frequency=c(53,13,23,31))

What I would like to have is a matrix that would have generated the above distribution. Is there a quick way to do it?

Claudio Moneo
  • 489
  • 1
  • 4
  • 10
  • 1
    Also see this answer: https://stackoverflow.com/questions/54787908/generate-data-frame-from-frequency-table – Ben Mar 26 '20 at 14:11

1 Answers1

0

How about this apply approach?

B <- apply(A,1,function(x){matrix(c(x[1],x[2]),ncol = 2, nrow = as.numeric(x[3]), byrow = TRUE)})
B <- do.call(rbind,B)
colnames(B) <- c("Age","Health")
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
  • That would work, but what if we have 10 different variables in the contingency table? I am looking for a quick way to do it regardless of the number of dimensions... ideally using a single function – Claudio Moneo Mar 26 '20 at 14:13
  • Yeah, in that case, use `data.frame.table` as recommended by @Ben. – Ian Campbell Mar 26 '20 at 14:24