giacomoV giacomoV - 3 months ago 14
R Question

R - dplyr stylised print or paste

I was wondering if it was possible to "stylised"

dplyr
results.

Imagine I am running a bootstrapping mean procedure 10 times, each time selecting 2 cases

library(dplyr)

for(i in 1:10){
m = mean( mtcars[sample(1:nrow(mtcars), size = 2), 'cyl'] )
print(paste('Mean Boot', i, ':', m))
}

[1] "Mean Boot 1 : 8"
[1] "Mean Boot 2 : 7"
[1] "Mean Boot 3 : 8"
[1] "Mean Boot 4 : 4"
...


I was wondering how I could print such results from a
dplyr
code.

Something like

for(i in 1:10){
mtcars %>% sample_n(2) %>%
summarise(m = mean(cyl)) %>%
print(paste('Mean Boot', i, ':', m))
}


Any clue ?

Answer

We can do

for(i in 1:10){ 
   mtcars %>%
   sample_n(2) %>% 
   summarise(m= paste('Mean Boot', i, ':', mean(cyl)))  %>%
   .$m %>%
   print 
 } 
#[1] "Mean Boot 1 : 6"
#[1] "Mean Boot 2 : 5"
#[1] "Mean Boot 3 : 7"
#[1] "Mean Boot 4 : 6"
#[1] "Mean Boot 5 : 8"
#[1] "Mean Boot 6 : 6"
#[1] "Mean Boot 7 : 4"
#[1] "Mean Boot 8 : 7"
#[1] "Mean Boot 9 : 8"
#[1] "Mean Boot 10 : 6"
Comments