Re: [R] Simple but elusive - expand back from counts

From: Petr Savicky <savicky_at_praha1.ff.cuni.cz>
Date: Tue, 29 Mar 2011 21:18:06 +0200

On Tue, Mar 29, 2011 at 11:15:33AM -0700, jjap wrote:
> Dear R-users,
>
> This should be simple but still eludes me:
>
> Given the following
> tmp<-as.data.frame(matrix(c(44, 10, "abc", 1, 44, 10, "def", 1, 44, 12,
> "abc", 2), 3, 4, byrow=T))
>
> I want to expand the data to the following form:
>
> V1 V2 V3 V4
> 1 44 10 abc 1
> 2 44 10 def 1
> 3 44 12 abc 1
> 4 44 12 abc 1
>
> The last row of the original df was duplicated the row by the number in the
> 4th column (which could be expendable being all ones)

Hi.

Try the following.

  tmp1 <- tmp[rep(1:nrow(tmp), times=tmp$V4), ]   tmp1$V4 <- 1
  row.names(tmp1) <- NULL
  tmp1

    V1 V2 V3 V4
  1 44 10 abc 1
  2 44 10 def 1
  3 44 12 abc 1
  4 44 12 abc 1

Hope this helps.

Petr Savicky.



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 29 Mar 2011 - 19:24:54 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 29 Mar 2011 - 19:30:24 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive