如何捕获参数到函数并在其他上下文/环境中原样应用它们

时间:2019-06-30 01:43:24

标签: r tidyeval

我很确定我的语言不准确,但是我还不知道正确的用语。这是我想要实现的:

我有一个函数boxplot(Value~Type+Level, data=Mydata2, ylim=c(-40,140)) 。我想获取用户提供的参数(无需评估或更改参数),以用于其他功能。例如

CREATE TABLE Artists (ID INT, ArtistName VARCHAR(255));
CREATE TABLE Albums (ID INT, ArtistID INT, AlbumName VARCHAR(255));
CREATE TABLE Performers (ID INT, ArtistID INT, PerformerName VARCHAR(255));
CREATE TABLE AlbumPerformers (ID INT, AlbumID INT, singer INT, guitar INT, bass INT, drumer INT);

使得调用SELECT Artists.ArtistName, Albums.AlbumName, PerformerSinger.PerformerName as Singer, PerformerDrumer.PerformerName as Drumer, PerformerGuitar.PerformerName as Guitar, PerformerBass.PerformerName as Bass FROM Artists INNER JOIN Albums ON Albums.ArtistID = Artists.ID INNER JOIN AlbumPerformers ON AlbumPerformers.AlbumID = Albums.ID INNER JOIN Performers AS PerformerSinger on AlbumPerformers.singer = PerformerSinger.ID INNER JOIN Performers AS PerformerDrumer on AlbumPerformers.drumer = PerformerDrumer.ID INNER JOIN Performers AS PerformerGuitar ON AlbumPerformers.guitar = PerformerGuitar.ID INNER JOIN Performers AS PerformerBass ON AlbumPerformers.bass = PerformerBass.ID; 与调用

相同
+------------+-----------+----------------+--------+-------------+-----------------+                                                                                         
| ArtistName | AlbumName | Singer         | Drumer | Guitar      | Bass            |                                                                                         
+------------+-----------+----------------+--------+-------------+-----------------+                                                                                         
| Beatles    | Revolver  | Paul McCartney | Ringo  | John Lennon | George Harrison |                                                                                         
+------------+-----------+----------------+--------+-------------+-----------------+   

并且调用import seaborn as sns, numpy as np x = np.random.randn(100) ax = sns.distplot(x) 与调用

相同
kde = False

基本上,我想从abc2移植abc2并应用它们,而无需改变用户输入和应用到其他地方的方式。

欢迎R和tidyeval说明!我正在尝试阅读abc2 <- function(...) { # what do I have to do here? } adf = data.frame(a = 1:3, b = 1:3) bdf = data.frame(a = 11:13, b = 11:33) abc2(a),但似乎无法理解。

1 个答案:

答案 0 :(得分:4)

1)以R 为基础通过...。可以使用"a"或仅使用a。这里的传递机制仅使用基数R。dplyr仅用于使我们可以使用select

library(dplyr)

adf = data.frame(a = 1:3, b = 1:3)
bdf = data.frame(a = 11:13, b = 21:23)

abc2 <- function(...) {
  print(select(adf, ...))
  print(select(bdf, ...))
}

# or: abc2(a)
abc2("a")

给予:

  a
1 1
2 2
3 3
   a
1 11
2 12
3 13

2)rlang 这也可以,但是这次我们使用rlang的enquos和!!!与tidyeval一起被dplyr吸引。

abc2a <- function(...) {
  dots <- enquos(...)
  print(select(adf, !!!dots))
  print(select(bdf, !!!dots))
}
abc2(a)