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

时间:2012-08-23 12:18:04

标签: r dataframe

我有一个这样的数据框:

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

帮助。

3 个答案:

答案 0 :(得分:4)

如果你愿意,你可以避免循环(而且它更像是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

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

答案 1 :(得分: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

答案 2 :(得分: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
相关问题