This is not a complicated problem, and I have a solution, but I can’t shake the feeling that there is a better way:
I have a data.frame with a tally of successes and opportunities by category, like this:
testFrame <- data.frame(successes = c(100, 150, 18),
opportunities = c(215, 194, 40),
category = LETTERS[1:3])
testFrame$category <- as.character(testFrame$category)
I want to convert this to a “tall” data.frame, with one column of 1s and 0s indicating success/failure and a second with category labels. I can do this with the following code:
tallFrame <- lapply(1:nrow(testFrame), function(rr){
cbind(rep(c(1, 0), c(testFrame[rr, "successes"], testFrame[rr, "opportunities"]-testFrame[rr, "successes"])), testFrame[rr, "category"])
})
tallFrame <- data.frame(do.call(rbind, tallFrame))
The resulting tallFrame is a matrix which I can then convert to a data.frame without any issues, but this seems like a lot of code for a simple task. Surely there is a way to do this more code-efficiently, perhaps with plyr or reshape, or maybe I’m just looking for some code golf.
Thanks in advance.
One does wonder why you need to do this, but regardless…
A
basesolution usingrepA
data.tablesolution (coding elegance (perhaps a code golf competitor)