在R magrittr管道的末尾使用$符号返回向量 [英] Use $ dollar sign at end of of an R magrittr pipeline to return a vector

查看:89
本文介绍了在R magrittr管道的末尾使用$符号返回向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 magrittr / tidyverse的末尾使用 $ 管道。 $ 直接在 tidyverse 函数(例如 read_csv filter ,但是一旦我使用%>%创建管道,就会引发错误。这是一个简单的可复制示例。

I'd like to use $ at the end of a magrittr/tidyverse pipeline. $ works directly next to tidyverse functions like read_csv and filter, but as soon I create a pipeline with %>% it raises an error. Here is a simple reproducible example.

# Load libraries and create a dummy data file
library(dplyr)
library(readr)
write_csv(data_frame(x=c(0,1), y=c(0,2)), 'tmp.csv')

# This works
y <- read_csv('tmp.csv')$y
str(y)

# This also works
df_y <- read_csv('tmp.csv')
y <- filter(df_y, y > 0)$y
str(y)

# This does not work
y <- read_csv('tmp.csv') %>% filter(y > 0)$y

我的问题是:

1)为什么在管道末端使用 $ 的基本解释/机理是什么?不起作用?

1) What are the underlying explanations/mechanics for why using $ at the end of a pipepline does not work?

2)什么是我要完成的最佳实践方法?具体来说,要获取向量作为管道的最终结果?

2) What's a best practice way for what I am trying to accomplish? Specifically, to get a vector as the end result of a pipeline?

推荐答案

它不起作用,因为它认为函数是 $ ,而不是 filter ,并尝试运行:

It does not work because it thinks that the function is $, not filter, and tries to run:

"$"(., filter(y > 0), y)

这当然是没有意义的。

which, of course, makes no sense.

假设 DF 如下所示。然后任何后续代码行均按预期工作:

Suppose DF is as shown below. Then any of the subsequent lines of code work as expected:

DF <- data.frame(y = seq(-3, 3))

DF %>% filter(y > 0) %>% "$"(y)
## [1] 1 2 3

DF %>% { filter(., y > 0)$y }
## [1] 1 2 3

DF %>% filter(y > 0) %>% "[["("y")
## [1] 1 2 3

library(magrittr) # supplies extract2 as an alias for [[
DF %>% filter(y > 0) %>% extract2("y")
## [1] 1 2 3

这篇关于在R magrittr管道的末尾使用$符号返回向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆