Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

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.

like image 829
bulafu collins Avatar asked Aug 23 '12 12:08

bulafu collins


People also ask

How do you create a DataFrame using conditions?

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.


3 Answers

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.

like image 138
dickoa Avatar answered Oct 04 '22 02:10

dickoa


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
like image 22
Andy Avatar answered Oct 04 '22 02:10

Andy


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
like image 29
Blue Magister Avatar answered Oct 04 '22 03:10

Blue Magister