[R] reshape data, adding rows to dataframe
Petr Savicky
savicky at praha1.ff.cuni.cz
Wed Feb 2 12:00:56 CET 2011
On Wed, Feb 02, 2011 at 01:13:11AM -0800, Lucia Rueda wrote:
>
> Hello everyone,
>
> I have a data set like this:
>
> > head( fish_transect)
> ID_TRANSECT ID_PROJECT DE_ZONE DE_LOCALITY DE_SECTOR MES
> 1 42 MB Tarragona Creixell Control I 9
> 2 42 MB Tarragona Creixell Control I 9
> 3 42 MB Tarragona Creixell Control I 9
> 4 42 MB Tarragona Creixell Control I 9
> 5 42 MB Tarragona Creixell Control I 9
> 6 42 MB Tarragona Creixell Control I 9
> ID_SPECIES WEIGHT SIZE N FAMILIA
> 1 Spondyliosoma cantharus 15.64 10 1 Sparidae
> 2 Symphodus melanocercus 11.21 10 1 Labridae
> 3 Diplodus vulgaris 30.20 10 2 Sparidae
> 4 Diplodus vulgaris 52.24 12 2 Sparidae
> 5 Diplodus sargus 221.41 14 5 Sparidae
> 6 Diplodus annularis 3.47 6 1 Sparidae
>
> I have been trying to duplicate the rows where N> 1, that is I want a row
> for each animal. Right now as you can see I have for example 5 D. sargus
> which are 14 cm length and so on. How can I get 1 row for each animal? I've
> been trying the reshape function without success. I also tried in access but
> couldn't do it either.
Hello.
Let me use a simpler example for testing.
dat <- data.frame(animal=c("a", "b", "c"), N=c(2, 1, 3))
dat
animal N
1 a 2
2 b 1
3 c 3
Is the following operation what you want in terms of this small example?
expand <- dat[rep(1:nrow(dat), times=dat$N), ]
rownames(expand) <- NULL
expand
animal N
1 a 2
2 a 2
3 b 1
4 c 3
5 c 3
6 c 3
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list