此问题出现在 dplyr
版本 0.30 中。
我有一个以过滤器
开头的管道链%>%
。有时,此过滤器会将数据帧减少到没有行。在管道的更深处,我有一个使用 if
来改变数据帧的函数。但是,如果数据帧之前已减少到零行,则此函数会出错。
例如
data(mtcars)
stupid_function <- function(x){
if( x == 6){
return(2*x)
} else {
return(x)
}
}
for(i in 6:10) {
data <-
mtcars %>%
filter(cyl == i) %>%
rowwise() %>%
mutate(carb2 = stupid_function(carb)) %>%
group_by(carb2) %>%
summarise(mean(wt))
print(data)
}
适用于 i = 6
,但适用于 i = 7
,例如
有什么办法可以解决这个问题吗?我考虑过的两种方法是打破中间的链以检查过滤后数据是否有多于一行,或者将所有内容包装在 tryCatch
中。
最佳答案
首先,在最新版本的dplyr
(0.4.0)中,过滤器不再崩溃,而是returns its input when the output is 0-sized (参见#782),这样你可能就不会再出现错误了。具体来说:
library(dplyr)
data(mtcars)
stupid_function <- function(x){
if(x == 6){
return(2 * x)
} else {
return(x)
}
}
for(i in 6:10) {
data <-
mtcars %>%
filter(cyl == i) %>%
rowwise() %>%
mutate(carb2 = stupid_function(carb)) %>%
group_by(carb2) %>%
summarise(mean(wt))
print(data)
}
返回:
Source: local data frame [3 x 2]
carb2 mean(wt)
1 1 3.33750
2 4 3.09375
3 12 2.77000
Source: local data frame [0 x 2]
Variables not shown: carb2 (dbl), mean(wt) (dbl)
Source: local data frame [4 x 2]
carb2 mean(wt)
1 2 3.560000
2 3 3.860000
3 4 4.433167
4 8 3.570000
Source: local data frame [0 x 2]
Variables not shown: carb2 (dbl), mean(wt) (dbl)
Source: local data frame [0 x 2]
Variables not shown: carb2 (dbl), mean(wt) (dbl)
Warning messages:
1: Grouping rowwise data frame strips rowwise nature
2: Grouping rowwise data frame strips rowwise nature
3: Grouping rowwise data frame strips rowwise nature
4: Grouping rowwise data frame strips rowwise nature
5: Grouping rowwise data frame strips rowwise nature
您可能还想在 stupid_function
中捕获 0 大小的输入,如下所示:
stupid_function <- function(x = NULL) {
if (is.null(x)) {
return(0)
} else if(x == 6) {
return(2 * x)
} else {
return(x)
}
}
这会将 NULL 预先分配给 x 并分配 0(或者您可以分配 NULL)作为返回(如果没有其他内容填充它)。
关于r - 如何处理在 dplyr 管道中进一步产生空数据的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913888/