[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.