Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Two equivalent commands give different returns in r

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading