2

I am trying to answer how many fields in each row is less than 5 using a pipe. In the following form it works (without pipe):

rowSums(   iris[,1:4]  < 5  ) # works!

But, trying to ask the same question using a pipe does not work:

iris[1:5,1:4] %>%  rowSums(  . <5  ) # wrong: returns the total rowsum
iris[,1:4] %>%  rowSums(   < 5  )   # does not work either.

Edit1: This workaround by user 'docendo discimus' solves this:

iris %>% mutate(sumVar = rowSums(.[1:4]<5))

Edit2: I like 'docendo discimus's workaround better because it avoids nested parenthesis:

iris %>%
  slice(1:5) %>%

  select(1:4) %>%

  dplyr::mutate( "New_var" = 10 ) %>% dplyr::mutate( "sumvar" = rowSums(. < 5 ) ) 

While the following solution (AFAICS) requires a nested parenthesis to work (plus I can't figure out how to get the new column mutated on the dataframe)

(iris %>%
   slice(1:5) %>%

   select(1:4) %>%

   dplyr::mutate( "New_var" = 10 )  < 5 )  %>% rowSums(.)
Community
  • 1
  • 1
Rasmus Larsen
  • 5,721
  • 8
  • 47
  • 79

1 Answers1

4
iris[1:5, 1:4] %>% is_less_than(5) %>% rowSums
# 1 2 3 4 5 
# 3 4 4 4 3 

would be magrittr equivalent to (no need in dplyr here)

rowSums(iris[1:5, 1:4] < 5)  
# 1 2 3 4 5 
# 3 4 4 4 3 
David Arenburg
  • 91,361
  • 17
  • 137
  • 196