Vectorizing loop over vector elements

后端 未结 3 2198
时光取名叫无心
时光取名叫无心 2021-02-20 01:12

I find it hard to come up with a fast solution to the following problem:

I have a vector of observations, which indicates the time of observation of certain phenomena. <

3条回答
  •  长情又很酷
    2021-02-20 01:34

    I suspect that your 0 values are actually NA values. Here I make them NA and than use na.locf (Last Observation Carried Forward) from package zoo:

    example <- c(0,0,0,1,0,1,1,0,0,0,-1,0,0,-1,-1,0,0,1,0,0)
    res <- example
    #res[res==0] <- NA
    #the same but faster
    res <- res/res*res
    library(zoo)
    res <- na.locf(res,  na.rm = FALSE)
    res[is.na(res)] <- 0
    cbind(example, res)
    #       example res
    #  [1,]       0   0
    #  [2,]       0   0
    #  [3,]       0   0
    #  [4,]       1   1
    #  [5,]       0   1
    #  [6,]       1   1
    #  [7,]       1   1
    #  [8,]       0   1
    #  [9,]       0   1
    # [10,]       0   1
    # [11,]      -1  -1
    # [12,]       0  -1
    # [13,]       0  -1
    # [14,]      -1  -1
    # [15,]      -1  -1
    # [16,]       0  -1
    # [17,]       0  -1
    # [18,]       1   1
    # [19,]       0   1
    # [20,]       0   1
    

提交回复
热议问题