Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two equivalent commands give different returns in r

Tags:

r

tidyverse

Why do the following two commands not return the same output?

x <- sample(0:1, 50, replace = TRUE, prob = c(0.5, 0.5))
  sum(x==1)

sample(0:1, 50, replace = TRUE, prob = c(0.5, 0.5)) %>%
  sum(.==1)

The first of the 2 command always gives me the right answer (something around 25) and the 2nd command returns a number that is way too high like 52. What did I understand wrong about the pipe operator here?

like image 976
Dave Twickenham Avatar asked Nov 29 '21 17:11

Dave Twickenham


1 Answers

Just wrap it with {}

sample(0:1, 50, replace = TRUE, prob = c(0.5, 0.5)) %>%
   {sum(.==1)}

The issue is that .==1 is considered as a second argument. It can be matched if we do

sum(x, x == 1)

As we are doing sample, make sure to specify the set.seed as well

set.seed(24)
x <- sample(0:1, 50, replace = TRUE, prob = c(0.5, 0.5))
  sum(x==1)

set.seed(24)
sample(0:1, 50, replace = TRUE, prob = c(0.5, 0.5)) %>%
   {sum(.==1)}
like image 55
akrun Avatar answered Oct 19 '22 23:10

akrun