crysis405
crysis405

Reputation: 1131

R loop through name and element

So far I only have 5 of these for each line, but soon I will have over 20 so I need to find a better way to do this. I was thinking of for loops but I don't know how to iterate over the numbers on the names (mt1, mt2, and so on).

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

Upvotes: 0

Views: 167

Answers (1)

agstudy
agstudy

Reputation: 121568

You can use lapply, for example:

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

Here you get a list of data.frame which is much better than having separate variables.

Note that paste("file", 1:No.file, sep=" ") is identical for all the data.frame's.

EDIT

In this case it is better to loop over , this will handle the case when dataoutput has length==0 and avoid error like 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")
})

Upvotes: 4

Related Questions