[R] Simple but elusive - expand back from counts
Petr Savicky
savicky at praha1.ff.cuni.cz
Tue Mar 29 21:18:06 CEST 2011
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.
More information about the R-help
mailing list