【问题标题】:How can I use dplyr and magrittr to pipe a data manipulation into a function that requires a numeric vector?如何使用 dplyr 和 magrittr 将数据操作传递到需要数值向量的函数中?
【发布时间】:2015-06-05 01:04:29
【问题描述】:

我正在尝试使用 dplyr 和 magrittr 将数据操作通过管道传输到需要数字向量作为输入的函数中。具体来说,我希望我的管道结果进入 ecdf() 函数(它从向量生成经验累积分布函数)。

这是我想做的工作:

x = rnorm(100)
t = sample(c("A","B"), replace = TRUE)
df = data.frame(x,t)
df_ecdf = filter(df, x > 0) %>%
  filter(t == "A") %>%
  select(x) %>%
  as.vector() %>%
  ecdf()

但是,这不起作用,因为 ecdf() 给出了错误:

Error in `[.data.frame`(x, order(x, na.last = na.last, decreasing = decreasing)) : 
  undefined columns selected

这是有道理的,因为通过 as.vector() 的管道实际上不会产生数据向量。它会生成一个列表,我不知道如何使用管道将其转换为数字向量。

任何帮助将不胜感激。

编辑

正如下面 BrodieG 的回答,解决方案是在 ecdf 之前通过管道输入 unlist,并且也不需要括号(根据 Ananda Mahto):

df_ecdf = filter(df, x > 0) %>%
  filter(t == "A") %>%
  select(x) %>%
  unlist %>%
  ecdf

【问题讨论】:

    标签: r type-conversion dplyr


    【解决方案1】:

    由于您需要 dplyr / magrittr 解决方案,您可以使用 magrittr 的 %$% 运算符,该运算符专为将 data.frame 的列提取为向量这一特定任务而设计:

    library(dplyr); library(magrittr)
    
    df_ecdf = filter(df, x > 0) %>%
      filter(t == "A") %$%
      x %>%
      ecdf
    

    【讨论】:

      【解决方案2】:

      使用unlist?

      filter(df, x > 0) %>%
        filter(t == "A") %>%
        select(x) %>%
        unlist %>%
        ecdf
      

      或者:

      filter(df, x > 0) %>%
        filter(t == "A") %>%
        `[[`("x") %>%
        ecdf
      

      但是,您应该考虑将base R 用于此类任务:

      ecdf(subset(df, x > 0 & t == "A", x, drop=T))
      

      或者即使你必须:

      df %>% subset(x > 0 & t == "A", x, drop=T) %>% ecdf
      

      【讨论】:

      • 如果我没记错的话,() 是不必要的 (+1)
      • magrittr 提供了许多别名函数,可以替换 [[[ 等。例如,extract2[[ 的别名,因此您可以使用 @ 987654333@ 而不是第二个解决方案中的'[['("x")
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      相关资源
      最近更新 更多