Tero
Tero

Reputation: 139

Counting number of occurrences in R

I'm learning R and I face a problem I don't know how to solve. I have an input subset similar to the following, with a client_id and 7 integers:

(client_id, 10, 8, -5, 8, 1, -23, 12)

I would like return the same vector but with an additional fields. First, one containing the number of times any of the other values are negative. For the above example, the result would be:

(client_id, 10, 8, -5, 8, 1, -23, 12, 2)

because there are just 2 negative numbers in the 7 integers.

A second field would be the number of values that are 0

(client_id, 10, 8, -5, 8, 1, -23, 12, 2, 3)

because there are 3 values between 0 and 10.

Can anyone help me with this issue?

Thanks a lot.

Upvotes: 0

Views: 644

Answers (2)

Pop
Pop

Reputation: 12411

If your vector is x it would be

x <- c(x, length(which(x[-1]<0)), length(which(x[-1]>=0 & x[-1]<=10)))

To answer to @Nishanth : you can also do

x <- c(x, sum(x[-1]<0), sum(x[-1]>=0 && x[-1]<=10))

Upvotes: 0

Harpal
Harpal

Reputation: 12587

How about this:

> t <- c("client_id", 10, 8, -5, 8, 1, -23, 12) # create vector
> nums <- as.numeric(t[2:length(t)]) # get numbers only from vector
> sum(nums < 0) # Counts the numbers less that 0
[1] 2
> sum(nums > 0 & nums < 10) # counts the number > 0 and < 10
[1] 3
> t <- append(t,sum(nums < 0)) # append to original vector
> t <- append(t,sum(nums > 0 & nums < 10))
> t
 [1] "client_id" "10"        "8"         "-5"        "8"         "1"         "-23"       "12"        "2"         "3"        
> 

Upvotes: 1

Related Questions