Shubhangi Sharma
Shubhangi Sharma

Reputation: 117

Check whether the data in column1 lies in a range And add data in column 2

I have a data frame in R containing 2 columns. I want to check whether the data in column one lies in the following range: x>80,70

count1
   Var1    Freq
1  0.00000   7
2  10.00000  1
3  16.66667  1
4  30.95238  1
5  33.33333  2

Data frame contains 32 rows in total with values in column 1 ranging from 0 to 100. output should be something like this :

    Var1      Freq
1   x<60      12
2   60<x<70   *something*
3   70<x<80   *something*
4   x>80      *something*

Upvotes: 2

Views: 64

Answers (1)

Mostafa90
Mostafa90

Reputation: 1706

With the datatable library

df is your dataframe :

breaks <- c(0,60,70,80,Inf)
setDT(df)
df[,list(SUM = sum(freq)),by = list(VAR=cut(var1,breaks = breaks))][order(VAR)]

With dplyr library :

 df %>% 
     group_by(VAR = cut(var1, breaks = breaks)) %>% 
     summarise(SUM = sum(freq)) %>%
     arrange(VAR)

Upvotes: 2

Related Questions