使用R中的前一个数字删除/替换列表中的值
我试图用列表中的前一个数字替换所有的零 列表如下所示:使用R中的前一个数字删除/替换列表中的值,r,R,我试图用列表中的前一个数字替换所有的零 列表如下所示: x <- c(3,0,0,0,0,1,0,0,0,0,0,2,0,0,0,0,3,0,0,0,1,0,2,0) 用NA替换d全零后,可以使用approx approx(replace(x, x == 0, NA), xout = 1:length(x), method = "constant", f = 0, rule = 2)$y # [1] 3 3 3 3 3 1 1 1 1 1 1 2 2 2 2 2 3 3 3
x <- c(3,0,0,0,0,1,0,0,0,0,0,2,0,0,0,0,3,0,0,0,1,0,2,0)
用
NA
替换d全零后,可以使用approx
approx(replace(x, x == 0, NA),
xout = 1:length(x), method = "constant", f = 0, rule = 2)$y
# [1] 3 3 3 3 3 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 1 1 2 2
用NA
替换d全零后,可以使用approx
approx(replace(x, x == 0, NA),
xout = 1:length(x), method = "constant", f = 0, rule = 2)$y
# [1] 3 3 3 3 3 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 1 1 2 2
可以修改
可以修改
您的预期输出是什么?库(zoo);na.locf(ifelse(x==0,na\u real\ux))
您的预期输出是什么?库(zoo);na.locf(ifelse(x==0,na\u real\ux))
approx(replace(x, x == 0, NA),
xout = 1:length(x), method = "constant", f = 0, rule = 2)$y
# [1] 3 3 3 3 3 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 1 1 2 2
fill = function(x){
ave(x, cumsum(x != 0), FUN = function(y) y[pmax(1, cumsum(y != 0))])
}
fill(x)
# [1] 3 3 3 3 3 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 1 1 2 2