pipe - R piping (%>%) does not work with replicate function -


i trying learn piping function (%>%).
when trying convert line of code line not work.

---- r code -- original version -----

set.seed(1014) replicate(6,sample(1:8))      [,1] [,2] [,3] [,4] [,5] [,6] [1,]    1    3    7    4    5    1 [2,]    2    8    4    2    4    2 [3,]    5    4    8    5    8    5 [4,]    3    1    2    1    1    7 [5,]    4    6    3    7    7    3 [6,]    6    5    1    3    3    8 [7,]    8    7    5    8    6    6 [8,]    7    2    6    6    2    4 

---- r code - recoded pipe ----

> sample(1:8) %>%  replicate(6,.)      [,1] [,2] [,3] [,4] [,5] [,6] [1,]    7    7    7    7    7    7 [2,]    3    3    3    3    3    3 [3,]    2    2    2    2    2    2 [4,]    1    1    1    1    1    1 [5,]    5    5    5    5    5    5 [6,]    4    4    4    4    4    4 [7,]    8    8    8    8    8    8 [8,]    6    6    6    6    6    6 

notice when using pipes, sampling not work giving me same vector across.

that's expected. replicate expects expression, when using pipe operator paste result of call sample() replicate. 6 times same result.

you have use quote() pass expression replicate instead of result, shouldn't forget evaluate each of repetitions of expression.

quote(sample(c(1:10,-99),6,rep=true)) %>%    replicate(6, .) %>%   sapply(eval) 

gives:

    [,1] [,2] [,3] [,4] [,5] [,6] [1,]    5    2   10   10    9    2 [2,]    4    3    1    3  -99    1 [3,]   10    2    3    8    2    4 [4,]  -99    1    6    2   10    3 [5,]    8  -99    1    9    4    6 [6,]    4   10    8    1  -99    8 

what happens here:

  • the piping sends , expression replicate without evaluating it.
  • replicate replicates expression , returns list 6 times expression without evaluating it.
  • sapply(eval) goes through list , executes each expression in list.

in previous question (i.e. when using data.frame), have done eg:

quote(sample(c(1:10,-99),6,rep=true)) %>%    replicate(6, .) %>%   data.frame 

now function data.frame force expressions executed, end terrible variable names, i.e. expression itself.

if want learn more issues here, you'll have dive called "lazy evaluation" , how dealt pipe operator. in honesty, don't see advantage of using pipe operator in case. it's not more readable.

as per frank's comment: can use mixture of piping , nesting of functions avoid sapply. that, have contain nested functions inside code block or pipe operator won't process correctly:

quote(sample(c(1:10,-99),6,rep=true)) %>% {   replicate(6, eval(.)) } 

very interesting, imho not useful...


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -