# [R] frequency of numbers in a list

Phil Spector spector at stat.berkeley.edu
Sat Aug 8 10:41:33 CEST 2009

```Julius -
Both mag and i are vectors, but of different lengths.
R interprets the statement mag>=i as "return a vector the
same length as mag and i whose elements compare the
corresponding elements of the two vectors."  The error
message is due to the fact that mag and i are of different
lengths. R  will repeat the shorter vector until it matches
the length of the longer vector, and reports a warning if it
can't use all the elements resulting from repeating them.
Basically the way you're calculating freq is as

sum(mag >= c(i,i[1:8])

Since the length of i is 32 and the length of mag is 40,
when it tries to repeat i, its' length becomes 40 so there
are some elements left over and the message is printed.

What you want is a vector the length of i, which compares each
element of i to *all* the elements of mag and then takes the sum.
In R, that would be done with

> sapply(i,function(x)sum(mag >= x))
[1] 40 39 39 39 39 38 37 35 34 32 30 29 28 28 24 20 18 15 14 13 11  8  5  5  4
[26]  3  2  2  2  2  1  1

Alternatively you could let R vectorize your function:

> vfun = Vectorize(function(x)sum(mag >= x))
> vfun(i)
[1] 40 39 39 39 39 38 37 35 34 32 30 29 28 28 24 20 18 15 14 13 11  8  5  5  4
[26]  3  2  2  2  2  1  1

Hope this helps.
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu

On Fri, 7 Aug 2009, Julius Tesoro wrote:

> Hi,
>
> I have two vectors, mag and i, and I want to generate a of vector  where each element is the frequency of mag which is greater than i.
>
> i produced the following code. However I get the following error:
>
> mag<-rnorm(40,5,3)
> i<-seq(floor(min(mag)),max(mag), 0.5)
> freq<-sum(mag>=i)
>
> Warning message:
> In mag >= i :
>  longer object length is not a multiple of shorter object length
>
> What's wrong with this code?
>
> Thank you very much.
>
> Cheers,
>
> Julius Tesoro
>
> ______________________________________________
> 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.
>

```