combine unequal length matrices in loop with cbind()
I have a simple question but it cost me hours. I would like to cbind() a matrix and a dataframe. The point is, they don't have equal lengths.
matrix:
condition
[,1]
ILMN_1666845 TRUE
ILMN_1716400 TRUE
Data.frame
a
t1 t2 t3 t4 1 0 1 1 1
If I use cbind() without a loop, everything is ok and this is the result:
b<-cbind(condition,a) b
condition t1 t2 t3 t4
ILMN_1666845 TRUE 0 1 1 1
ILMN_1716400 TRUE 0 1 1 1
But in a for loop I get the following error: Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 0, 1
Can anyone help me? Thanks!
For loop code:
for (p in 1:nrow(outcomes)) {
id <- apply(regulationtable, 1, function(i)
sum(i[1:length(regulationtable)] != outcomes[p,])==0)
idd<-as.matrix(id)
condition = subset(idd, idd[,1开发者_Go百科]==TRUE)
a<-as.data.frame(t(outcomes[p,]))
b<-cbind(condition,a)
write.table(b, "file.txt", append=TRUE)}
As far as I could read from your code, you try to cbind a possible empty object, which never works. That's also what the error is telling you. Probably at some point a
is just empty, as there are no matches. So just add a condition
if(sum(id) !=0) { ... }
You could benefit quite a lot from rewriting your code to take this into account. I tried to guess what you wanted to do, and this code does exactly the same :
xx <- apply(outcomes,1,function(p){
id <- apply(regulationtable,1,function(i)
sum(i != p ) == 0)
if(sum(id) !=0)
cbind(as.data.frame(id[id]),t(p))
})
write.table(do.call(rbind,xx),file="file")
It returns you a list xx with, for every possible outcome, the genes that have the same regulationpattern. This is tested with :
outcomes <- expand.grid(c(0,1),c(0,1),c(0,1),c(0,1))
regulationtable <- data.frame(
t1=sample(0:1,10,replace=T),
t2=sample(0:1,10,replace=T),
t3=sample(0:1,10,replace=T),
t4=sample(0:1,10,replace=T)
)
rownames(regulationtable) <- paste("Gene",1:10,sep="-")
精彩评论