我目前有一个相当复杂的数据集,但我试图对它进行分解,并希望手头的问题有足够的复杂性。
我的数据如下:
df <- data.frame(c(1,1,1,1,2,2,2,3,3,3), c(3,3,NA,5,0,0,0,7,4,7),
c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE,
TRUE, FALSE))
colnames(df) <- c("ID", "Number", "Status")
> df
ID Number Status
1 1 3 TRUE
2 1 3 TRUE
3 1 NA TRUE
4 1 5 FALSE
5 2 0 FALSE
6 2 0 FALSE
7 2 0 FALSE
8 3 7 FALSE
9 3 4 TRUE
10 3 7 FALSE我依次查看每个ID (使用dplyr group_by)。每当观察的状态为真时,我想将" number“替换为后续的number,并将其替换为FALSE。对于ID = 1,这将意味着所有4个观测值的数字5。
我已经找到了一个解决办法,但我确信肯定会有一个更简单的解决方案(使用替换?)。我就是这样做的:
library(dplyr)
library(zoo)
# Setting up a new variable that replaces all "unwanted
# numbers by NA
df$newNumber <- NA
df$newNumber[df$Status == FALSE] <- df$Number[df$Status == FALSE]
# Using the zoo function na.locf to replace the Gas
df <- df %>%
group_by(ID) %>%
mutate(Number2 = ifelse(any(Status == TRUE), na.locf(newNumber,
fromLast = TRUE), Number2))
> df
# A tibble: 10 x 5
# Groups: ID [3]
ID Number Status newNumber Number2
<dbl> <dbl> <lgl> <dbl> <dbl>
1 1 3 TRUE NA 5
2 1 3 TRUE NA 5
3 1 NA TRUE NA 5
4 1 5 FALSE 5 5
5 2 0 FALSE 0 0
6 2 0 FALSE 0 0
7 2 0 FALSE 0 0
8 3 7 FALSE 7 7
9 3 4 TRUE NA 7
10 3 7 FALSE 7 7非常感谢您提前!
发布于 2019-03-18 17:50:14
你可以这样做:
library(zoo)
df$Number[df$Status==TRUE] <- NA #replace Number with NA for all Status = TRUE
df$Number <- na.locf(df$Number, fromLast = TRUE)
ID Number Status
1 1 5 TRUE
2 1 5 TRUE
3 1 5 TRUE
4 1 5 FALSE
5 2 0 FALSE
6 2 0 FALSE
7 2 0 FALSE
8 3 7 FALSE
9 3 7 TRUE
10 3 7 FALSEData.table解
library(data.table)
setDT(df)
df[Status==TRUE, Number:=NA_real_]
df[,Number:=na.locf(Number, fromLast=TRUE, na.rm = FALSE)]https://stackoverflow.com/questions/55227096
复制相似问题