Skip to content

How to Un-group a grouped data set?

6 messages · R. Michael Weylandt, Cheenghee AM Koh, David L Carlson

#
Don't use subset for a function name -- it's already the name of a
rather important function as is data (but at least that one's not a
function in your use so it's not quite so bad). Finally, use dput()
when sending data so we get a plaintext reproducible version.

I'd try something like this:

dats <- structure(list(Study = c(1L, 1L, 2L, 2L, 3L, 3L), TX = c(1L,
0L, 1L, 0L, 1L, 0L), AEs = c(3L, 2L, 1L, 2L, 1L, 1L), N = c(5L,
7L, 10L, 7L, 8L, 4L)), .Names = c("Study", "TX", "AEs", "N"), class =
"data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))

# See how handy dput can be :-)

dats[unlist(mapply(FUN = function(x,y) rep(x, y), 1:NROW(dats), dats$N)), -4]

which isn't super elegant, but others might have something better.

Best,
Michael
On Tue, May 15, 2012 at 1:24 AM, Cheenghee AM Koh <sigontw at gmail.com> wrote:
#
Sorry -- I missed the bit about the AE in your original post. Perhaps
you can work with my bit for the repeats, but it looks like if you
want to use your function, it should suffice to do something like

do.call("rbind", lapply(NewFuncName, 1:6))

Best,
Michael

On Tue, May 15, 2012 at 1:50 AM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
#
It is a nifty and surprisingly useful construct whenever you need to
construct a function call programmatically or apply it to a list.

R-News 2/2 has some useful tips on this and related functions in the
Programmer's Note section if you're interested.

Best,
Michael
On Tue, May 15, 2012 at 2:05 AM, Cheenghee AM Koh <sigontw at gmail.com> wrote:
#
newdats <- rbind(cbind(dats[rep(1:nrow(dats), dats$AEs), 1:2], 
  AEs=1), cbind(dats[rep(1:nrow(dats), dats$N-dats$AEs),1:2], 
  AEs=0))

But the data will not be in the order you specified unless you add

newdats <- newdats[order(newdats$Study, -newdats$TX, -newdats$AEs),]

and you may want to clean up the rownumbers with

rownames(newdats) <- 1:nrow(newdats)

----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352