【问题标题】:creating new variables with transform and %>%使用 transform 和 %>% 创建新变量
【发布时间】:2014-05-17 20:18:54
【问题描述】:

我正在尝试基于LETTERS 向量使用“管道式”运算符创建一个新变量,该变量的长度与数据框中的其他变量相同。出了点问题,我对magrittr 太陌生,无法诊断问题。

当我尝试使用一些“传统”嵌套函数时,我能够正确创建变量:

expand.grid(a=c(1000-500,1000,1000+500),
                       b=c(15,150)) %>%
  mutate(c=paste("foo", LETTERS[seq_along(a)],sep="_"))

##      a   b     c
## 1  500  15 foo_A
## 2 1000  15 foo_B
## 3 1500  15 foo_C
## 4  500 150 foo_D
## 5 1000 150 foo_E
## 6 1500 150 foo_F

然后我想我会尝试使用来自magrittrdplyr 的管道状%>%

expand.grid(a=c(1000-500,1000,1000+500),
                       b=c(15,150)) %>%
  mutate(c=paste("foo", a %>% 
                   seq_along %>% 
                   LETTERS[.],sep="_"))

## Error: incorrect number of dimensions

当我从 magrittr 添加别名提取 ([) 函数时,这也不起作用:

expand.grid(a=c(1000-500,1000,1000+500),
                       b=c(15,150)) %>%
  mutate(c=paste("foo", a %>% 
                   seq_along %>% 
                   extract(LETTERS,.),
                 sep="_"))

## Error: incorrect number of dimensions

我尝试使用debug_pipe 调试管道,但无济于事。如有任何想法,我将不胜感激!

【问题讨论】:

  • 原来. 与来自plyr.() 混淆了。拆下那个包,一切正常。

标签: r dplyr magrittr


【解决方案1】:

如果你愿意,你可以:

expand.grid(a=1000+c(-500, 0, 500), b=c(15,150)) %>%
mutate(c = a %>% seq_along %>% LETTERS[.] %>% paste0("foo_", .))

【讨论】:

  • 如此优雅!您是否知道是否有任何计划可以减少 ..() 混淆的可能性?
  • 我无法复制 .() 问题。仅加载 plyr 和 magrittr,您的版本和我的版本都可以正常工作。
【解决方案2】:

如果我们定义一个辅助函数Swap,那么它可以不使用 .像这样:

library(dplyr)
library(magrittr)

Swap <- function(f) function(x, y, ...) f(y, x, ...)

expand.grid(a=1000+c(-500, 0, 500), b=c(15,150)) %>%
  mutate(c = a %>% 
             seq_along %>% 
             Swap(extract)(LETTERS) %>% 
             Swap(paste0)("foo_"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多