首页 > 解决方案 > 数据重组帮助:如何确定“事件”之间的最大天数并复制该值

问题描述

我找不到回答这个特定问题的线程,因此将不胜感激。我有一个看起来像这样的数据集,其中变量“EventCount”计算数据集中每个人发生的事件之间的天数(如果 EventCount=0,则事件已经发生)。

Day = c(1:8,1:8)
EventCount = c(NA,NA,0,1,2,0,1,0,0,1,2,3,0,1,2,0)
Person = c(1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2)
dat <- data.frame(Person,Day,EventCount);dat

我正在尝试重新构建数据集,以便它获取每个人发生的事件之间的最大值,并复制或填充该值。我希望它看起来像这样:

NewEvent = c(NA,NA,0,2,2,0,1,0,0,3,3,3,0,2,2,0)
dat2 <- dat <- data.frame(Person,Day,NewEvent);dat2

提前致谢!

标签: rvariablesif-statementdataframe

解决方案


由于这有点复杂,我会编写一个函数来修改数据框。像这样的东西会起作用,但我敢肯定会有一个“哇,这很简单”的方法。

fillDays <- function(df){
    df$NewEvent <- df$EventCount

    max <- 0
    updateFrom <- 1
    for (i in 1:nrow(df)) {

        if(i %% 8 == 1){ # for each person
            max <- 0
        }
        val <- dat$EventCount[i]

        if(is.na(val)){ # If NA, no updates, just start from next record
            updateFrom =  updateFrom + 1 

        } else if(val == 0) { # If 0, set max to previous records

            if(updateFrom != i){
                df[updateFrom : (i-1), 'NewEvent'] <- max
            }
            max <- 0
            updateFrom = i + 1                

        } else { # update the max 
            if(val > max){
                max <- val
            }
        }
    }

    return(df)
}

> fillDays(dat)

#    Person Day EventCount NewEvent
# 1       1   1         NA       NA
# 2       1   2         NA       NA
# 3       1   3          0        0
# 4       1   4          1        2
# 5       1   5          2        2
# 6       1   6          0        0
# 7       1   7          1        1
# 8       1   8          0        0
# 9       2   1          0        0
# 10      2   2          1        3
# 11      2   3          2        3
# 12      2   4          3        3
# 13      2   5          0        0
# 14      2   6          1        2
# 15      2   7          2        2
# 16      2   8          0        0

对于不同的天数,

fillDays <- function(df){
    df$NewEvent <- df$EventCount

    max <- 0
    updateFrom <- 1
    Person <- 1
    for (i in 1:nrow(df)) {

        if(df$Person[i] != Person){
            max <- 0
            Person <- df$Person[i]
        }
        val <- dat$EventCount[i]

        if(is.na(val)){
            updateFrom =  updateFrom + 1

        } else if(val == 0) {

            if(updateFrom != i){
                df[updateFrom : (i-1), 'NewEvent'] <- max
            }
            max <- 0
            updateFrom = i + 1


        } else {
            if(val > max){
                max <- val
            }
        }
    }

    return(df)
}

推荐阅读