Retain and lag function in R as SAS

后端 未结 4 603
礼貌的吻别
礼貌的吻别 2021-01-05 10:05

I am looking for a function in R similar to lag1, lag2 and retain functions in SAS which I can use with data.tables.

I know th

4条回答
  •  囚心锁ツ
    2021-01-05 10:43

    For retain, try this :

    retain<-function(x,event,outside=NA)
    {
      indices <- c(1,which(event==TRUE), nrow(df)+1)
      values <- c(outside,x[event==TRUE])
      y<- rep(values, diff(indices)) 
    }
    

    With data : I want to retain down the value when w==b

    df <- data.frame(w = c("a","b","c","a","b","c"), x = 1:6, y = c(1,1,2,2,2,3), stringsAsFactors = FALSE)
    df$z<-retain(df$x-df$y,df$w=="b")
    df
    

    And here's the contrary obtain, that does not exist in SAS:

    obtain<-function(x,event,outside=NA)
    {
      indices <- c(0,which(event==TRUE), nrow(df))
      values <- c(x[event==TRUE],outside)
      y<- rep(values, diff(indices)) 
    }
    

    Here's an example. I want to obtain the value in advance where w==b

    df$z2<-obtain(df$x-df$y,df$w=="b")
    df
    

    Thanks to Julien for helping.

提交回复
热议问题