[R] counting the number of ones in a vector
Gavin Simpson
gavin.simpson at ucl.ac.uk
Sat Feb 27 11:54:52 CET 2010
On Fri, 2010-02-26 at 10:43 -0800, David Reinke wrote:
> The length will remain the same no matter what expression appears in
> the subscript.
No it won't! x == 1 evaluates to logical and when used to *subset* x, it
*will* return the required answer. As observed with this example:
> set.seed(1)
> x <- sample(rep(1:3, times = 20))
> x
[1] 1 1 1 1 3 2 3 3 3 1 2 3 3 1 2 2 2 1 3 2 2 1 1 2 1 2 1 1 1 1
[31] 3 3 2 3 2 2 2 3 3 3 1 3 3 1 3 2 1 1 2 2 1 1 3 2 2 3 2 2 3 3
>
> ## compare
> sum(x == 1, na.rm = TRUE)
[1] 20
> length(x)
[1] 60
> length(x[x == 1])
[1] 20
G
> I suggest this:
>
> sum(x == 1)
>
> David Reinke
>
> Senior Transportation Engineer/Economist
> Dowling Associates, Inc.
> 180 Grand Avenue, Suite 250
> Oakland, California 94612-3774
> 510.839.1742 x104 (voice)
> 510.839.0871 (fax)
> www.dowlinginc.com
>
> Please consider the environment before printing this e-mail.
>
> Confidentiality Notice: This e-mail message, including any attachments, is for the sole use of the intended recipient(s), and may contain confidential and privileged information. Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message.
>
>
>
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Randall Wrong
> Sent: Friday, February 26, 2010 6:44 AM
> To: r-help at r-project.org
> Subject: [R] counting the number of ones in a vector
>
> Dear R users,
>
> I want to count the number of ones in a vector x.
>
> That's what I did : length( x[x==1] )
>
> Is that a good solution ?
>
> Thank you very much,
> Randall
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Dr. Gavin Simpson [t] +44 (0)20 7679 0522
ECRC, UCL Geography, [f] +44 (0)20 7679 0565
Pearson Building, [e] gavin.simpsonATNOSPAMucl.ac.uk
Gower Street, London [w] http://www.ucl.ac.uk/~ucfagls/
UK. WC1E 6BT. [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
More information about the R-help
mailing list