[R] frequency count by row

Sarah Goslee sarah.goslee at gmail.com
Tue Mar 6 18:56:35 CET 2012


A reproducible example would be helpful, but lacking that
here's some untested code. If your data frame has NA values,
those will also need to be dealt with.

apply(mydata, 1, function(x)sum(x != 0))


Sarah

On Tue, Mar 6, 2012 at 12:03 PM, mari681 <marianna.bolognesi at gmail.com> wrote:
> I feel this is a very easy thing but I've never done it before and it is
> getting frustrating.
> I have a big data.frame (1445846 rows,  15 col)
>  that looks like this:
>
>                V1          V2         V3          V4          V5
>
> 1    home      sister        brother   chair       0
> 2    cat             dog          animal      0           0
> 3    girl            boy           0                0           0
> 4    knife      fork          spoon          0            0
>
> and I want to count how many values different from 0 are in each row, and
> get the output count in a vector that is as long as length(MyTable). For the
> above example it would be c (4,3,2,3).
> I've tried   sum (MyTable != "0") but it gives the total amount of values
> different from 0 in all the data.frame.
> And sum(MyTable [1,] != "0") obviously gives only the first row, even if I
> repeat it throughout all length(MyTable).
> How does that work?
>
> Thank you,
>
> a newbie.
>
>

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list