ℕʘʘḆḽḘ
ℕʘʘḆḽḘ

Reputation: 19375

printing one element of a dataframe in a magrittr pipe

Consider this simple example

library(dplyr)
library(glue)
library(magrittr)

> mydata <- data_frame(value = c(1,2,3))
> mydata
# A tibble: 3 x 1
  value
  <dbl>
1    1.
2    2.
3    3.

I would like to print the second element of my column value2 in my dataframe from within a magrittr pipe.

I know I can exploit the tee operator in magrittr, but as you can see below my code does not work:

  1. it does not print anything
  2. it does not extract the value itself. Indeed"the second element of value2 is 1" is merely a string. I also tried some variants with glue::"the second element of {} is {}" without success.

For instance,

> mydata %>% mutate(value2 = value - 1) %T>% 
    print('the second element of value2 is 1') %>% 
    summarize(count = n())
# A tibble: 3 x 2
  value value2
  <dbl>  <dbl>
1    1.     0.
2    2.     1.
3    3.     2.
# A tibble: 1 x 1
  count
  <int>
1     3

Any ideas how to do that programmatically? Thanks!

Upvotes: 2

Views: 715

Answers (1)

Frank
Frank

Reputation: 66819

With sprintf:

nm = "value2"
mydata %>% mutate(value2 = value - 1) %T>% {
  cat(sprintf('the second element of %s is %s.\n', nm, nth(.[[nm]], 2))) } %>% 
  summarize(count = n())

the second element of value2 is 1.
# A tibble: 1 x 1
  count
  <int>
1     3

Or with glue

nm = "value2"
mydata %>% mutate(value2 = value - 1) %T>% {
  x = nth(.[[nm]], 2)
  cat(glue('the second element of {nm} is {x}.\n\n')) } %>% 
  summarize(count = n())

the second element of value2 is 1.
# A tibble: 1 x 1
  count
  <int>
1     3

For some reason, glue eats the first newline (\n).

The {} are needed since "egad" %T>% print("some words") evaluates to print("egad", "some words") according to magrittr semantics.

Upvotes: 3

Related Questions