基于另一个数据框(使用循环或其他方法)创建新的数据框

5

I have a data frame like this:

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

我想根据times的值重复行。我考虑使用循环来创建以下新数据框:
Site   speciescode   abundance
LM1    MkI           9
LM1    MkI           9
LM1    MkI           9
LM2    KiU           8
LM2    KiU           8
LM2    KiU           8
LM2    KiU           8

帮助。


编辑你的问题。我希望你是想问这样的问题。我认为这可能对更多人有帮助。 - Stat-R
3个回答

4

如果你想的话,可以避免循环(这更符合R语言的风格)。

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

您也可以使用@BlueMagister的方法更改丰度值。

哦,很好。从速度上来讲,这可能更有效率。 - Blue Magister

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

1

请尝试以下方法(根据需要编辑行号):

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接