for循环,在每次迭代后输出唯一的数据帧

时间:2017-03-16 21:50:33

标签: r for-loop

我知道R中必须有一个简单的方法来在For循环中迭代这个过程,但我在编写循环方面很新。这是我想用循环

完成的过程
sfus1a<-ddply(sfus,.(Phylum),nrow);sfus1a[1,1]
sfus1b<-subset(sfus,sfus$Phylum==sfus1a[1,1])
sfus1<-ddply(sfus1b,.(Genus),nrow);sfus1

sfus1a<-ddply(sfus,.(Phylum),nrow);sfus1a[2,1]
sfus1b<-subset(sfus,sfus$Phylum==sfus1a[2,1])
sfus2<-ddply(sfus1b,.(Genus),nrow);sfus2

sfus1a<-ddply(sfus,.(Phylum),nrow);sfus1a[3,1]
sfus1b<-subset(sfus,sfus$Phylum==sfus1a[3,1])
sfus3<-ddply(sfus1b,.(Genus),nrow);sfus3

sfus1a<-ddply(sfus,.(Phylum),nrow);sfus1a[4,1]
sfus1b<-subset(sfus,sfus$Phylum==sfus1a[4,1])
sfus4<-ddply(sfus1b,.(Genus),nrow);sfus4

所以输出应该是四个数据帧sfus1,sfus2,sfus3和sfus4

我尝试编写的以下循环不起作用

for(i in 1:4){
  sfus1a<-ddply(sfus,.(Phylum),nrow);sfus1a[i,1]
  sfus1b<-subset(sfus,sfus$Phylum==sfus1a[i,1])
  sfusi<-ddply(sfus1b,.(Genus),nrow);sfusi
}

1 个答案:

答案 0 :(得分:2)

首先创建一个列表,否则for循环将在每次迭代时覆盖变量

# pre-allocate lists
sfus1a <- vector(mode = "list", length = nrow(sfus))
sfus1b <- vector(mode = "list", length = nrow(sfus))
sfusi <- vector(mode = "list", length = nrow(sfus))

for(i in 1:4){
  sfus1a[i] <- ddply(sfus, .(Phylum), nrow)
  sfus1b[i] <- subset(sfus, sfus$Phylum == sfus1a[i, 1])
  sfusi[i] <- ddply(sfus1b, .(Genus), nrow)
}

由于没有针对

进行测试的样本数据集,因此可能需要稍微调整一下