How to count how many elements satisfy a condition in an idiomatic way?

Having this data:

> data
 [1] 1290603356 1290603360 1290603350 1290603344 1290603340 1290603373
 [7] 1290603354 1290603359 1290603345 1290603363 1290603357 1290603354
[13] 1290603364 1290603349 1290603352 1290603365 1290603349 1290603343
[19] 1290603339 1290603343
> offsets <- c(0, 0.5,1,2,4,8,24,4*24,7*24) * 3600)
[1]   1800   3600   7200  14400  28800  86400 345600 604800
> myoffsets <- min(data)+offsets

being, a list of UNIX epochs and a list of offsets (0.5 hours, 1h, 2h, 4h...) I want to be able to graph how many of the epochs are <= than the min(data) + offset

In this example it would be

1 20 20 20 20 20 20 20

I have found how to do this with a for loop:

for(i in c(1:length(myoffsets))) myres$x[i] <- length(data[data <= myoffsets[i]])

But I'm sure there's a more idiomatic way if doing this that is not as convoluted?


Suggestion 1: A slightly more idiomatic way would be to replace

length(data[data <= myoffsets[i]])


sum(data <= myoffsets[i])

This way you don't end up taking a subset of data for each value in myoffsets, only to compute its length and discard.

Suggestion 2: The c() in the for is redundant. The following would do exactly the same with fewer keystrokes: for(i in 1:length(myoffsets)).

Lastly, if you prefer to get rid of the explicit loop, something like this might be to your taste:

myres$x <- sapply(myoffsets, function(o)sum(data<=o))

Need Your Help

How can I keep templates out of /js/?

backbone.js requirejs

I'm using RequireJS 2 along with backbone and pals to build the website. The beginning of every view is usually something like this:

What is the relation/difference between Amazon DynamoDB and FlockDB?

machine-learning amazon-dynamodb pagerank montecarlo flockdb

I am trying to implement incremental PageRank using Monte Carlo Sampling. My data includes millions of relational data between 20 different entities.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.