Reputation:
The problem
I would like to find a length of a list.
The expected output
I would like to find the length based on a condition.
Example
Suppose that I have a list of 4 elements as follows:
myve <–list(1,2,3,0)
Here I have 4 elements, one of them is zero. How can I find the length by extracting the zero values? Then, if the length is > 1
I would like to substruct one. That is:
If the length is 4
then, I would like to have 4-1=3
. So, the output should be 3
.
Note
Please note that I am working with a problem where the zero values may be changed from one case to another. For example, For the first list may I have only one 0 value, while for the second list may I have 2 or 3 zero values.
The values are always positive or zero.
Upvotes: 0
Views: 679
Reputation: 12411
You just need to apply the condition to each element. This will produce a list of boolean, then you sum it to get the number of True
elements (i.e. validation your condition).
In your case:
sum(myve != 0)
In a more complex case, where the confition is expressed by a function f
:
sapply(myve, f)
Upvotes: 2
Reputation: 799
Use sapply to extract the ones different to zeros and sum to count them
sum(sapply(myve, function(x) x!=0))
Upvotes: 0