R 数据重组帮助:如何确定';事件';并复制该值
我找不到一条线索来回答这个特定的问题,所以我将不胜感激。 我有一个类似这样的数据集,其中变量“EventCount”统计数据集中每个人发生事件之间的天数(如果EventCount=0,则事件已发生)R 数据重组帮助:如何确定';事件';并复制该值,r,variables,if-statement,dataframe,R,Variables,If Statement,Dataframe,我找不到一条线索来回答这个特定的问题,所以我将不胜感激。 我有一个类似这样的数据集,其中变量“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,2,2,2,2,2,2,2) dat由于这是一个有点复杂的更改,我将编写一个函数来修改数据帧。像这样的方法会奏效,但我相信会有一
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,2,2,2,2,2,2,2)
dat由于这是一个有点复杂的更改,我将编写一个函数来修改数据帧。像这样的方法会奏效,但我相信会有一种“哇,那很简单”的方法
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非常感谢,对于我提供的示例数据,此函数确实有效。但在我的实际数据集中,并不是每个人都有8天,有些人可能会有更多或更少的时间。我认为这个功能只有在每个人有8天的时间时才有效。有没有一个简单的方法来修改函数,使其允许这样做?更新了答案。非常感谢-我已经批准了你的答案!
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
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)
}