R循环通过名称和元素

时间:2013-03-08 09:33:29

标签: r loops for-loop

到目前为止,我每行只有5个,但很快我就会超过20个,所以我需要找到一个更好的方法来做到这一点。我在考虑for循环,但我不知道如何迭代名称上的数字(mt1,mt2等)。

mt1<- do.call(cbind, dataoutput[[1]])
mt2<- do.call(cbind, dataoutput[[2]])
mt3<- do.call(cbind, dataoutput[[3]])
mt4<- do.call(cbind, dataoutput[[4]])
mt5<- do.call(cbind, dataoutput[[5]])

rownames(mt1)[1:No.file]<-paste("file", 1:No.file, sep=" ")
rownames(mt2)[1:No.file]<-paste("file", 1:No.file, sep=" ")
rownames(mt3)[1:No.file]<-paste("file", 1:No.file, sep=" ")
rownames(mt4)[1:No.file]<-paste("file", 1:No.file, sep=" ")
rownames(mt5)[1:No.file]<-paste("file", 1:No.file, sep=" ")

library(reshape)
mt11<-melt(mt1, id.vars="Legend")
mt21<-melt(mt2, id.vars="Legend")
mt31<-melt(mt3, id.vars="Legend")
mt41<-melt(mt4, id.vars="Legend")
mt51<-melt(mt5, id.vars="Legend")

1 个答案:

答案 0 :(得分:4)

您可以使用lapply,例如:

lapply(1:5,function(i){
       mt <- do.call(cbind, dataoutput[[i]])
       rownames(mt)[1:No.file]<- paste("file", 1:No.file, sep=" ")
       mt.melt <-melt(mt, id.vars="Legend")
})

这里有一个data.frame的列表,它比单独的变量要好得多。

请注意,paste("file", 1:No.file, sep=" ")对于所有data.frame都是相同的。

编辑

在这种情况下,最好循环,这将处理dataoutput长度== 0时的情况,并避免像subscript out of bounds

这样的错误
lapply(dataoutput,function(do){
       mt <- do.call(cbind, do)
       rownames(mt)[1:No.file]<- paste("file", 1:No.file, sep=" ")
       mt.melt <-melt(mt, id.vars="Legend")
})
相关问题