2017-03-16 117 views
0

我知道R中必須有一個簡單的方法來在For循環中迭代這個過程,但我在編寫循環方面相當新穎。下面是我嘗試寫不工作,我想用一個循環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 

完成所以輸出應該有四個dataframes 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 
} 

回答

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) 
} 

這可能需要稍微調整,因爲沒有樣本數據集要測試

相關問題