[R] How to count numbers of a vector and use them as index values?

Jeffrey Dick j3ffdick at gmail.com
Mon Aug 1 00:19:20 CEST 2011


Here's an attempt using sapply:

> x <- c(2, 2, 3, 3, 4, 6)
> ys <- 1:8
> sapply(ys, function(y) { length(which(x==y)) } )
[1] 0 2 2 1 0 1 0 0

Jeff

On Sun, Jul 31, 2011 at 2:41 PM, Paul Menzel
<paulepanter at users.sourceforge.net> wrote:
> Dear R folks,
>
>
> I am sorry to ask this simple question, but my search for the right
> way/command was unsuccessful.
>
> I have a vector
>
>> x <- c(2, 2, 3, 3, 4, 6)
>
> Now the values of x should be considered the index of another vector
> with possible greater length, say 8, and the value should be how often
> the indexes appeared in the original vector x.
>
>> length(result)
>  [1] 8
>> result
>  [1] 0 2 2 1 0 1 0 0
>
>
> Thank you in advance,
>
> Paul
>
> ______________________________________________
> 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.
>
>



More information about the R-help mailing list