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?
CodePudding user response:
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)}