This is working, thanks!
I have a table like this,
gene1 a 2 0 1 0
gene2 b 5 0 2 2
gene3 a 7 4 0 0
I want to count the number of non-zero elements in rows and columns and append it to the same table. This is how I did it for rows: myfile$rowsum <- rowSums(myfile[4:6] != 0). For columns I am trying to make this one work, but it starts from the 1st column and not the 4th: rbind(myfile, colSums(myfile != 0)) Not sure how to append it and how to move starting from column 4. So i want something like this
gene1 a 2 0 1 0 1
gene2 b 5 0 2 2 2
gene3 a 7 4 0 0 1
1 2 1
2 answers
This is how I did it for rows: myfile$rowsum <- rowSums(myfile[4:6] !=0)
Shouldn't it be rowSums(myfile[,4:6]) ?
For columns I am trying to make this one work, but it starts from the 1st column and not the 4th: rbind(myfile, colSums(myfile != 0))
Try rbind(myfile, c("colsum", "NA", "NA", colSums(myfile[,4:6] != 0)))
Here's what I came up with - there are probably much better ways of doing this.
> zeros <- which(table ==0, arr.ind = T)
row col [1,] 1 4 [2,] 2 4 [3,] 3 5 [4,] 1 6 [5,] 3 6
> colcount = array(0,dim = ncol(table)-1)
> rowcount = array(0,dim = nrow(table))
> for(i in b[,2]){colcount[i-1]=colcount[i-1]+1}
> for(i in b[,1]){rowcount[i]=rowcount[i]+1}
> b <- cbind(table,rowcount)
> b <- rbind(b,c("",colcount,""))
giving you
b rowcount [1,] "gene1" "a" "2" "0" "1" "0" "2" [2,] "gene2" "b" "5" "0" "2" "2" "1" [3,] "gene3" "a" "7" "4" "0" "0" "2" [4,] "" "0" "0" "4" "2" "4" ""
Log in to answer this question.