如何使用 dplyr 和 magrittr 将数据操作通过管道传输到需要数字向量的函数中?
How can I use dplyr and magrittr to pipe a data manipulation into a function that requires a numeric vector?
我正在尝试使用 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
使用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
由于您要求的是 dplyr / magrittr 解决方案,因此您可以使用 magrittr 的 %$%
运算符,该运算符专为将 data.frame 的列提取为向量的特定任务而设计:
library(dplyr); library(magrittr)
df_ecdf = filter(df, x > 0) %>%
filter(t == "A") %$%
x %>%
ecdf
我正在尝试使用 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
使用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
由于您要求的是 dplyr / magrittr 解决方案,因此您可以使用 magrittr 的 %$%
运算符,该运算符专为将 data.frame 的列提取为向量的特定任务而设计:
library(dplyr); library(magrittr)
df_ecdf = filter(df, x > 0) %>%
filter(t == "A") %$%
x %>%
ecdf