I'm trying to use a conditional lead
/lag
function in a dplyr pipe using ifelse but getting an error. However, using the same approach outside the pipe it seems to work. What am I missing?
我正在尝试使用ifelse在dplyr管道中使用条件超前/滞后函数但是会出错。但是,在管道外使用相同的方法似乎可行。我错过了什么?
require(dplyr)
Data:
数据:
test <- data.frame(a = c("b","b","b","b","b","b",
"m","m","m","m","m","m",
"s","s","s","s","s","s"),
b = replicate(1,n=18),
stringsAsFactors=F)
dplyr pipe:
dplyr管道:
test %>%
mutate(delta = ifelse(a == "s", b + lag(b, n = 2*6),
ifelse(a == "m", b + lag(b, n = 1*6), 0)))
# Error: could not convert second argument to an integer. type=LANGSXP, length = 3
Without the pipe it works:
没有管道它工作:
test$delta <- ifelse(test$a == "s", test$b + lag(test$b, n = 2*6),
ifelse(test$a == "m", test$b + lag(test$b, n = 1*6), 0))
I found some indication that there was an issue with dplyr lead
/lag
in combination with grouped data frames. But I am not grouping here.
我发现有一些迹象表明dplyr超前/滞后与分组数据帧有关。但我不是在这里分组。
Version info: R 3.1.1 and dplyr_0.4.1.
版本信息:R 3.1.1和dplyr_0.4.1。
2 个解决方案
#1
1
dplyr
fails to parse the expression. One solution is to define the function first:
dplyr无法解析表达式。一种解决方案是首先定义函数:
foo <- function(a, b)
ifelse(a=="s",b+lag(b,n=2*6), ifelse(a=="m",b+lag(b,n=1*6),0))
test %>% mutate(delta = foo(a,b))
#2
4
This:
这个:
test %>%
mutate(delta = ifelse(a=="s",b+lag(b,n=12),
ifelse(a=="m",b+lag(b,n=6),0)))
works. This means that you cannot pass expressions in lag
arguments.
作品。这意味着您无法在滞后参数中传递表达式。
#1
1
dplyr
fails to parse the expression. One solution is to define the function first:
dplyr无法解析表达式。一种解决方案是首先定义函数:
foo <- function(a, b)
ifelse(a=="s",b+lag(b,n=2*6), ifelse(a=="m",b+lag(b,n=1*6),0))
test %>% mutate(delta = foo(a,b))
#2
4
This:
这个:
test %>%
mutate(delta = ifelse(a=="s",b+lag(b,n=12),
ifelse(a=="m",b+lag(b,n=6),0)))
works. This means that you cannot pass expressions in lag
arguments.
作品。这意味着您无法在滞后参数中传递表达式。