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.
You can create a conditional DataFrame column by checking multiple columns using numpy. select() function. The select() function is more capable than the previous methods. We can use it to give a set of conditions and a set of values.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With