开发者

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]])

with

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))


plot(subset(data, data <= min(data+offset)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜