Search code examples
rcountvectorizationzero

Removing rows with less than 4 non zero entries, without using loop


The dataset is like this:

"1" 10 40 "r" "q" "0" "r" "r" "0" "r" "0" "0" "0" "0" "0" "t" "q" "0" "0" "s" "0" "r" 0 "0" 0 "0" "0" 0 0 0 "0"
"2" 10 173 "s" "s" "s" "0" "0" "s" "s" "0" "t" "t" "s" "t" "t" "r" "s" "0" "q" "0" "0" 0 "0" 0 "0" "0" 0 0 0 "0"
"3" 10 2107 "t" "0" "0" "s" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" 0 "0" 0 "0" "0" 0 0 0 "0"
"4" 10 993 "s" "0" "q" "s" "s" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" 0 "0" 0 "0" "0" 0 0 0 "0"
"5" 10 1712 "t" "0" "s" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "s" "0" "t" "0" 0 "0" 0 "0" "0" 0 0 0 "0"
"6" 776 1872 "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" 0 "r" 0 "0" "0" 0 0 0 "s"

Output should be:

"1" 10 40 "r" "q" "0" "r" "r" "0" "r" "0" "0" "0" "0" "0" "t" "q" "0" "0" "s" "0" "r" 0 "0" 0 "0" "0" 0 0 0 "0"
"2" 10 173 "s" "s" "s" "0" "0" "s" "s" "0" "t" "t" "s" "t" "t" "r" "s" "0" "q" "0" "0" 0 "0" 0 "0" "0" 0 0 0 "0"
"4" 10 993 "s" "0" "q" "s" "s" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" 0 "0" 0 "0" "0" 0 0 0 "0"
"5" 10 1712 "t" "0" "s" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "s" "0" "t" "0" 0 "0" 0 "0" "0" 0 0 0 "0"

The code that I have tried is:

x=read.table("sample.txt")
nrowx=nrow(x) 
for(i in 1:nrowx)
{
    count=0
    for(j in 3:30)
    {
        if(x[i,j]!=0)
        count = count+1
    }   
    if(count<4)
    x[i,]=NA    
}  
x=x[complete.cases(x),]

Please suggest some method that doesn't involve loop.


Solution

  • It looks like none of your rows have less than four non-zero entries:

    For example, printing the number of nonzero entries per row with tab being your table:

    apply(tab, 1, function(x)sum(x!="0"))
     [1] 12 16  5  7  7  5
    

    To for example eliminate all rows which have less than 5 nonzero entries, you could do

    tab[-which(apply(tab, 1, function(x)sum(x!="0"))<=5),]
    

    I am not sure if the first column in your data is treated as a column in your data frame, however.

    Does this help?