Another approach could be to move your logical operation to the sample() function
sample(c(0:1) == TRUE,
size = 50,
replace = TRUE,
prob = c(0.5, 0.5)) %>%
sum
You do ask why — the sum function will sum all the values it receives, not just the first vector. When you are piping, it takes the output of the last step to the first argument in sum(...)
so by also providing x==1
you are providing two vectors and essentially saying sum(x, x==1)
. You can see this with sum(c(1,1,1), c(1,1,1))
for example (which returns six, summing the all values in both vectors), or in your code:
set.seed(1)
x <- sample(0:1,
size = 50,
replace = TRUE,
prob = c(0.5, 0.5))
sum(x, x==1)
set.seed(1)
sample(0:1,
size = 50,
replace = TRUE,
prob = c(0.5, 0.5)) %>%
sum(x==1)
Further, if x <- c(1, 0, 1, 0, 1, 1)
, then sum(x, x==1)
or x %>% sum(x==1)
is effectively
sum(c(1, 0, 1, 0, 1, 1), as.numeric(c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE)))