Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Counting the number of a specific value in bins

Tags:

r

I have a data frame (df) like below:

Value <- c(1,1,0,2,1,3,4,0,0,1,2,0,3,0,4,5,2,3,0,6)
Sl <- c(1:20)
df <- data.frame(Sl,Value)    

> df
   Sl Value
1   1     1
2   2     1
3   3     0
4   4     2
5   5     1
6   6     3
7   7     4
8   8     0
9   9     0
10 10     1
11 11     2
12 12     0
13 13     3
14 14     0
15 15     4
16 16     5
17 17     2
18 18     3
19 19     0
20 20     6

I would like to create 4 bins out of df and count the occurrences of Value=0 grouped by Sl values in a separate data frame like below:

Bin Count
1   1
2   2
3   2
4   1

I was trying to use table and cut to create the desire data frame but its not clear how I'll specify df$Value and the logic to find the 0s here

df.4.cut <- as.data.frame(table(cut(df$Sl, breaks=seq(1,20, by=5))))
like image 819
Joarder Kamal Avatar asked Aug 13 '15 06:08

Joarder Kamal


People also ask

How do I count unique values in R?

Method 1: Using length(unique()) function Unique() function when provided with a list will give out only the unique ones from it. Later length() function can calculate the frequency.

How do you count occurrences in R?

To count occurrences between columns, simply use both names, and it provides the frequency between the values of each column. This process produces a dataset of all those comparisons that can be used for further processing. It expands the variety a comparison you can make.

How do you count the number of times a value appears in a column in R?

To count the number of times a value occurs in a column of an R data frame, we can use table function for that particular column.

How do I count columns in R?

The ncol() function in R programming That is, ncol() function returns the total number of columns present in the object.


1 Answers

Using your df

tapply(df$Value, cut(df$Sl, 4), function(x) sum(x==0))

gives

> tapply(df$Value, cut(df$Sl, 4), function(x) sum(x==0))
(0.981,5.75]  (5.75,10.5]  (10.5,15.2]    (15.2,20] 
           1            2            2            1 

In cut you can specify the number of breaks or the breaks itself if you prefer and the logic is in the function definition in tapply

like image 78
mts Avatar answered Oct 09 '22 07:10

mts