我更新了一个新的不同问题。这一次,我想从Oxy获取列Oxy2。
ID Oxy Y Oxy2
1 NA 2010 NA
1 0 2011 0
1 NA 2012 NA
1 1 2013 1
1 NA 2014 1
1 NA 2015 1
1 -1 2016 1
2 0 2011 0
2 NA 2012 NA
2 1 2013 1
2 -1 2014 1
3 0 2012 0
3 -1 2013 -1
3 NA 2014 NA
4 -1 2010 -1
4 1 2011 1
4 -1 2012 1
4 -1 2013 1
4 0 2014 1
4 NA 2015 1基本上,当Oxy变量之前的值为0或-1时,我需要保留NAs (如果有),并将第一个1之后的所有内容替换为1。
再次感谢您的建议。
发布于 2019-12-07 02:23:47
library(dplyr)
library(zoo)
df %>%
group_by(ID) %>%
mutate(Ins1=na.locf(ifelse(is.na(Ins) & lag(Ins)==0, 999, Ins), na.rm = FALSE), Ins2=na_if(Ins1, 999))
#one step version
#mutate(Ins1 = na_if(na.locf(ifelse(is.na(Ins) & lag(Ins)==0, 999, Ins), na.rm = FALSE), 999))
# A tibble: 8 x 5
# Groups: ID [2]
ID Ins Y Ins1 Ins2
<int> <int> <int> <dbl> <dbl>
1 1 0 2010 0 0
2 1 NA 2011 999 NA
3 1 1 2012 1 1
4 1 NA 2013 1 1
5 1 NA 2014 1 1
6 2 0 2011 0 0
7 2 0 2012 0 0
8 2 NA 2013 999 NA更新:为了解决这个问题,我对-1 \f25 @user12492692 -1\f6在-1\f25 Edit -1\f6中的建议添加了一个小改动,即用-1\f25 %in% -1\f6替换-1\f25 | -1\f6
df %>%
group_by(ID) %>%
mutate(Ins1 = na.locf(ifelse(is.na(Ins) & lag(Ins) %in% c(0,-1), 999, Ins), na.rm = FALSE),
Ins2 = na_if(Ins1, 999))发布于 2019-12-07 02:49:21
下面是另一个替代方法,它使用LOCF填充所有值,然后将NA的值添加到零后面:
library(dplyr)
df1 %>%
mutate(Ins_b = Ins[!is.na(Ins)][cumsum(!is.na(Ins))],
Ins_b = replace(Ins_b, is.na(Ins) & Ins_b == 0, NA))
ID Ins Y Ins_b
1 1 0 2010 0
2 1 NA 2011 NA
3 1 1 2012 1
4 1 NA 2013 1
5 1 NA 2014 1
6 2 0 2011 0
7 2 0 2012 0
8 2 NA 2013 NAhttps://stackoverflow.com/questions/59218151
复制相似问题