在magrittr管道中打印数据框的一个元素

时间:2018-03-07 18:11:51

标签: r dplyr magrittr

考虑这个简单的例子

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.

我想在value2管道中的数据框中打印我的列magrittr的第二个元素。

我知道我可以利用tee中的magrittr运算符,但正如您在下面看到的,我的代码不起作用:

  1. 它不会打印任何内容
  2. 它不会提取值本身。确实"the second element of value2 is 1"只是一个字符串。我还尝试了glue::"the second element of {} is {}"的一些变体但没有成功。
  3. 例如,

    > 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
    

    有任何想法如何以编程方式执行此操作? 谢谢!

1 个答案:

答案 0 :(得分:3)

使用sprintf:

"test.c"":""22"":"__FUNCTION__

或用胶水

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

出于某种原因,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 会占用第一个换行符(glue)。

根据magrittr语义,\n评估为{}时需要"egad" %T>% print("some words")