2013-12-10 3 views
0

내 데이터는 다음과 같은 형식이전 행의 값을 기반으로 새로운 변수를 형성

structure(list(Flag = c(1, 0, 0, 1, 0, 0, 1, 0), variable = c(3, 
8, 6, 7, 1, 4, 3, 6), sale = c(26, 27, 61, 38, 79, 87, 81, 13 
)), .Names = c("Flag", "variable", "sale"), row.names = c(NA, 
-8L), class = "data.frame") 

입니다 그리고 북동 열 시작과 끝

structure(list(Flag = c(1, 0, 0, 1, 0, 0, 1, 0), variable = c(3, 
8, 6, 7, 1, 4, 3, 6), sale = c(26, 27, 61, 38, 79, 87, 81, 13 
), begin = c(3, -23, -50, 7, -31, -70, 3, -78), end = c(-23, 
-50, -111, -31, -70, -151, -78, -91)), .Names = c("Flag", "variable", 
"sale", "begin", "end"), row.names = c(NA, -8L), class = "data.frame") 

을 기반으로 다음과 같이 I 출력을 만들려면 다음 알고리즘에 대해서

if flag=1 then 
    begin=variable; 
    end=variable-sale; 
---------- 
else 
begin=lag(end) (i.e the previous value of end variable) 
end= lag(end)-sale 

플래그가 1이면 "begin"의 값이 "variable"값과 동일합니다. "end"값은 "variable-sale"값입니다. 다른 사람에 관해서는 begin의 값은 이전 행의 "end"값이고 "end"값은 (begin-sales) 값 누구든지 R에서 이것을 달성하는 방법을 써주는 데 도움이 될 수 있습니까?

답변

3

은 당신이 제공하는 예제 출력이 잘못 생각하지만, 나는 다음과 같은 시도 할 것이다 :

beginEnd <- by(indf, cumsum(indf$Flag), FUN = function(x) { 
    out <- Reduce("-", c(x[, "variable"][1], x[, "sale"]), accumulate = TRUE) 
    cbind(begin = head(out, -1), 
     end = tail(out, -1)) 
}) 
cbind(indf, do.call(rbind, beginEnd)) 
# Flag variable sale begin end 
# 1 1  3 26  3 -23 
# 2 0  8 27 -23 -50 
# 3 0  6 61 -50 -111 
# 4 1  7 38  7 -31 
# 5 0  1 79 -31 -110 
# 6 0  4 87 -110 -197 
# 7 1  3 81  3 -78 
# 8 0  6 13 -78 -91 
관련 문제