Creating a new data frame based on another data frame (using a loop or otherwise)

I have a data frame like this:

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

I want to repeat the lines depending on the values times. I thought about using a loop to create a new data frame 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

Reference.

+5
source share
3 answers

You can avoid the loop if you want (and 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 the @BlueMagister method.

+4
source
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
+2
source

Try this (edit line numbers if 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
+1
source

All Articles