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 0
s here
df.4.cut <- as.data.frame(table(cut(df$Sl, breaks=seq(1,20, by=5))))
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.
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.
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.
The ncol() function in R programming That is, ncol() function returns the total number of columns present in the object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With