6

Surprisingly I am not finding an answer to this easy question. I need a pipe-friendly way to count the number of non-zero elements in a vector.

Without piping:

v <- c(1.1,2.2,0,0)
length(which(v != 0))

When I try to do this with pipes I get an error

v %>% which(. != 0) %>% length
Error in which(., . != 0) : argument to 'which' is not logical

A dplyr solution would also help

LucasMation
  • 2,408
  • 2
  • 22
  • 45
  • 1
    Related, more general post: [Using the %>% pipe, and dot (.) notation](https://stackoverflow.com/questions/42385010/using-the-pipe-and-dot-notation) – Henrik May 19 '20 at 17:07

3 Answers3

7

Here are some different options:

First, we can use {} with your original form:

v %>% {which(. != 0)} %>% length
#[1] 2

Or we could use {} to allow us to repeat .:

v %>% {.[. != 0]} %>% length
#[1] 2

Or we could use subset from Base R:

v %>% subset(. != 0) %>% length
#[1] 2
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
2

One way using magrittr could be:

v %>%
 equals(0) %>%
 not() %>%
 sum()

[1] 2
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
1

We can convert to tibble and filter

library(dplyr)
tibble(v) %>% 
  filter(v != 0) %>%
  nrow
#[1] 2
akrun
  • 874,273
  • 37
  • 540
  • 662