LucasMation
LucasMation

Reputation: 2489

Pipe/dplyr friendly way to filter non zero elements of a vector

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

Upvotes: 6

Views: 817

Answers (3)

akrun
akrun

Reputation: 887088

We can convert to tibble and filter

library(dplyr)
tibble(v) %>% 
  filter(v != 0) %>%
  nrow
#[1] 2

Upvotes: 1

tmfmnk
tmfmnk

Reputation: 39858

One way using magrittr could be:

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

[1] 2

Upvotes: 2

Ian Campbell
Ian Campbell

Reputation: 24790

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

Upvotes: 7

Related Questions