Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 961
user525602 Avatar asked Nov 30 '10 19:11

user525602


People also ask

How do you check if all elements in a list satisfy condition?

To check if all elements of a List satisfy a given condition/predicate in Kotlin, call all() function on this List object and pass the predicate as argument to this function. The Kotlin List. all() function checks if all the elements of the list match a given predicate, and returns a boolean value.

How do you count elements in a list with conditions in Python?

Use len() & List comprehension to count elements in list based on conditions. We can use list comprehension to create a new list of elements that satisfies our given condition and then get the length of this new list to find out number of elements in original list that satisfies our condition i.e.

How do you check if every element of a list satisfies a condition in python?

Use all() to check if every element of a list satisfies a condition. Use the syntax condition for item in list to build a generator expression that checks each item in list against a given condition .


1 Answers

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

like image 96
NPE Avatar answered Oct 05 '22 10:10

NPE