2017-05-04 2 views
2

나는 리드 타임이있는 주문과 매출 채권이 있습니다. dplyr를 사용하여 그룹 리드 타임에 따라 수신 열을 채울 수 있습니까?dplyr 그룹별로 지연하는 방법

df <- data.frame(team = c("a","a","a","a", "a", "b", "b", "b", "b", "b"), 
       order  = c(2, 4, 3, 5, 6, 7, 8, 5, 4, 5), 
       lead_time = c(3, 3, 3, 3, 3, 2, 2, 2, 2, 2)) 
>df 
    team order lead_time 
    a  2   3 
    a  4   3 
    a  3   3 
    a  5   3 
    a  6   3 
    b  7   2 
    b  8   2 
    b  5   2 
    b  4   2 
    b  5   2 

그리고 지금처럼 열을받을 추가 : 도움을 내가 오류에이 라인을 따라 생각하지만, 실행 된

dfb <- data.frame(team = c("a","a","a","a", "a", "b", "b", "b", "b", "b"), 
       order  = c(2, 4, 3, 5, 6, 7, 8, 5, 4, 5), 
       lead_time = c(3, 3, 3, 3, 3, 2, 2, 2, 2, 2), 
       receive = c(0, 0, 0, 2, 4, 0, 0, 7, 8, 5)) 

>dfb 
team order lead_time receive 
    a  2   3  0 
    a  4   3  0 
    a  3   3  0 
    a  5   3  2 
    a  6   3  4 
    b  7   2  0 
    b  8   2  0 
    b  5   2  7 
    b  4   2  8 
    b  5   2  5 

dfc <- df %>% 
     group_by(team) %>% 
     mutate(receive = if_else(row_number() < lead_time, 0, lag(order, n = lead_time))) 

Error in mutate_impl(.data, dots) : 
    could not convert second argument to an integer. type=SYMSXP, length = 1 

감사합니다!

답변

1

이것은 버그처럼 보입니다. dplyrstats 패키지 사이의 lag 기능의 일부 의도하지 않은 마스크가있을 수 있습니다,이 해결을 시도해보십시오

df %>% 
    group_by(team) %>% 
    # explicitly specify the source of the lag function here 
    mutate(receive = dplyr::lag(order, n=unique(lead_time), default=0)) 

#Source: local data frame [10 x 4] 
#Groups: team [2] 

#  team order lead_time receive 
# <fctr> <dbl>  <dbl> <dbl> 
#1  a  2   3  0 
#2  a  4   3  0 
#3  a  3   3  0 
#4  a  5   3  2 
#5  a  6   3  4 
#6  b  7   2  0 
#7  b  8   2  0 
#8  b  5   2  7 
#9  b  4   2  8 
#10  b  5   2  5 
1

우리는 또한 data.table

library(data.table) 
setDT(df)[, receive := shift(order, n = lead_time[1], fill=0), by = team] 
df 
#  team order lead_time receive 
# 1: a  2   3  0 
# 2: a  4   3  0 
# 3: a  3   3  0 
# 4: a  5   3  2 
# 5: a  6   3  4 
# 6: b  7   2  0 
# 7: b  8   2  0 
# 8: b  5   2  7 
# 9: b  4   2  8 
#10: b  5   2  5 
에서 shift을 사용할 수 있습니다
관련 문제