if statement - R: dplyr pipe conditional lead/lag using ifelse with unexpected behavior -


i'm trying use conditional lead/lag function in dplyr pipe using ifelse getting error. however, using same approach outside pipe seems work. missing?

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:

test %>%   mutate(delta = ifelse(a == "s", b + lag(b, n = 2*6),                         ifelse(a == "m", b + lag(b, n = 1*6), 0)))  # error: not convert second argument integer. type=langsxp, length = 3 

without pipe 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 indication there issue dplyr lead/lag in combination grouped data frames. not grouping here.

version info: r 3.1.1 , dplyr_0.4.1.

dplyr fails parse expression. 1 solution define function first:

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)) 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -