0

Is there a R function to count the values more than 0 in a row

  test <- data.frame(a=c(a,"y"),b=c(0,"5"),c=c(2,"0"))
  test
  a b c
1 1 0 2
2 y 5 0

I need to get following, because first row contains 1 values more than 0 and second row contains 1 value more than 0. I need to exclude first column as it is only character

test
  a b c d
1 a 0 2 1
2 y 5 0 1
Jana P
  • 25
  • 5
  • 1
    If you create `test` as `test <- data.frame(a=c(1,0),b=c(0,1),c=c(2,0))`, you can do `rowSums(test > 0)` – Ronak Shah Jul 10 '19 at 06:52
  • Well thanks. Sorry, a small change, lets say there is a character in the data sets. I need to exclude that and then count. Question edited – Jana P Jul 10 '19 at 07:12
  • `c(0,"5")` gives a character vector, i.e. the same as `c("0","5")` - so give us a reproducible example [mre] – jogo Jul 10 '19 at 07:17
  • @JanP Try this `type.convert(test, as.is = TRUE) %>% select_if(is.numeric) %>% is_greater_than(0) %>% rowSums` – akrun Jul 10 '19 at 07:20

1 Answers1

0

We can convert the type of columns with type.convert, select the numeric columns, check if it is greater than 0, get the row wise sum of logical matrix, and create a new column in the 'test' dataset

library(tidyverse)
library(magrittr)
type.convert(test, as.is = TRUE) %>%
    select_if(is.numeric) %>%
    is_greater_than(0) %>% 
    rowSums %>%
    bind_cols(test, d = .)
#  a b c d
#1 a 0 2 1
#2 y 5 0 1
akrun
  • 874,273
  • 37
  • 540
  • 662