elliezee
elliezee

Reputation: 133

Count values within a range by row in R

My data looks like this:

a<-c(-1,-4,-17,8,1)
b<-c(2,-2,-13,10,3)
c<-c(NA,0,NA,NA,5)
d<-c(NA,1,NA,NA,NA)
e<-c(NA,NA,NA,NA,NA)

mydata<-data.frame(a,b,c,d,e)

I would like to count the number of values within the range of -1 to 5 by row.

So the end product (myrow) should look like this:

mydata$myrow<-c(2,2,0,0,3)

I can probably create 5 dummies (ifelse something %in% c(-1:5) then 1, else 0) then count them. But there must be a more efficient way to do this.

Upvotes: 1

Views: 484

Answers (3)

akrun
akrun

Reputation: 886948

Using c_across from dplyr

library(dplyr)
mydata %>% 
  rowwise %>%
  mutate(myrow = sum(between(c_across(everything()), -1, 5), na.rm = TRUE)) %>%
  ungroup

-output

# A tibble: 5 x 6
#      a     b     c     d e     myrow
#  <dbl> <dbl> <dbl> <dbl> <lgl> <int>
#1    -1     2    NA    NA NA        2
#2    -4    -2     0     1 NA        2
#3   -17   -13    NA    NA NA        0
#4     8    10    NA    NA NA        0
#5     1     3     5    NA NA        3
 

Upvotes: 1

Adam Bricknell
Adam Bricknell

Reputation: 161

ThomasIsCoding's method looks simpler & vectorised (so faster). However for info, an alternative is to use apply() rowwise:

library(dplyr)
apply(mydata, 1, function(x) {between(x, -1, 5)}) %>% rowSums(na.rm = T)

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

You can try

mydata$myrow <- rowSums(mydata >= -1 & mydata <= 5, na.rm = TRUE)

which gives

> mydata
    a   b  c  d  e myrow
1  -1   2 NA NA NA     2
2  -4  -2  0  1 NA     2
3 -17 -13 NA NA NA     0
4   8  10 NA NA NA     0
5   1   3  5 NA NA     3

Upvotes: 1

Related Questions