5

I have a data frame like this:

Site    speciescode abundance   times
LM1           MkI        9      3
LM2           KiU        8      4

I want to repeat the rows depending on the times values. I was thinking of using a loop to make the new dataframe as follows:

Site   speciescode   abundance
LM1    MkI           9
LM1    MkI           9
LM1    MkI           9
LM2    KiU           8
LM2    KiU           8
LM2    KiU           8
LM2    KiU           8

Help.

1
  • Edit your question. I hope you meant to ask something like this. I thought this may be helpful to more people Commented Aug 24, 2012 at 1:42

3 Answers 3

4

You can avoid loop if you want (and it's more R'ish)

d <- data.frame(Site=c("LM1","LM2"),speciescode=c("MkI","KiU"),abundance=c(3,4),time=c(3, 4))

dnew <- d[rep(1:nrow(d), d$time), ]
dnew[ ,1:3]
##     Site speciescode abundance
## 1    LM1         MkI         3
## 1.1  LM1         MkI         3
## 1.2  LM1         MkI         3
## 2    LM2         KiU         4
## 2.1  LM2         KiU         4
## 2.2  LM2         KiU         4
## 2.3  LM2         KiU         4

You can also change the abundance value using @BlueMagister method.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, nifty. That's probably more efficient speed-wise.
2
df <- data.frame(Site=c("LM1","LM2"),speciescode=c("MkI","KiU"),abundance=c(9,8),times=c(3,4))
df <- df[rep(1:nrow(df), df$abundance),]
df$abundance <- rep(c(9,8), c(3,4))

#    Site speciescode abundance
#1    LM1         MkI         9
#1.1  LM1         MkI         9
#1.2  LM1         MkI         9
#2    LM2         KiU         8
#2.1  LM2         KiU         8
#2.2  LM2         KiU         8
#2.3  LM2         KiU         8

Comments

1

Try this (edit the row numbers as necessary):

d <- data.frame(Site=c("LM1","LM2"),speciescode=c("MkI","KiU"),abundance=c(3,4),times=c(3,4))
for(i in seq(from=3,to=7,by=2)) {
  d[i,] <- d[1,]
  d[i+1,] <- d[2,]
}
d$abundance[d$times == 3] <- 9
d$abundance[d$times == 4] <- 8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.