Home > Blockchain >  Count how many lines exceeded a certain value in R data frame
Count how many lines exceeded a certain value in R data frame

Time:11-15

I got a data frame and i want to count how many times each column is equal ou exceeds 0.61

Data = data.frame(  
  v1 = c(0.1, 0.2, 0.4, 0.7, 0.9),
  v2 = c(0.1, 0.12, 0.41, 0.72, 0.91),
  v3 = c(0.03, 0.13, 0.92, 0.61, 0.90))

My result should be:

Result = data.frame(v1 = 2,
                    v2 = 2,
                    v3 = 3)

Thanks!

CodePudding user response:

You can do

Results <- sapply(Data, function(x) sum(x >= 0.61))
Results
##  v1 v2 v3 
##   2  2  3 

If you really want to have a data.frame output, you can do

Results <- as.data.frame(lapply(Data, function(x) sum(x >= 0.61)))
Results
##    v1 v2 v3
##  1  2  2  3

CodePudding user response:

Here is a dplyr solution:

library(dplyr)
Data %>% 
  mutate(across(everything(), ~ifelse(. >=0.61, 1, 0))) %>% 
  summarise(across(everything(), ~ sum(., is.na(.), 0)))
  v1 v2 v3
1  2  2  3
  •  Tags:  
  • r
  • Related