Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 通过向量向后循环_R - Fatal编程技术网

R 通过向量向后循环

R 通过向量向后循环,r,R,我想直接计算向量中某个值之前的NAs数量。我目前正在尝试使用嵌套的“while”循环,因为它可以计算NAs的数量。这是我的代码和一个样本向量,我一直得到NA值的1: x <- c(1:10) x[3:6] <- NA for (i in 1:length(x)){ if (is.na(x[i])){ j <- i while (is.na(x[j])){ j <

我想直接计算向量中某个值之前的NAs数量。我目前正在尝试使用嵌套的“while”循环,因为它可以计算NAs的数量。这是我的代码和一个样本向量,我一直得到NA值的1:

x <- c(1:10)
x[3:6] <- NA
    for (i in 1:length(x)){
        if (is.na(x[i])){
            j <- i
                while (is.na(x[j])){
                j <- j - 1
                }
            x[i] <- j - i
         }
         else{
         x[i] <- x[i]
    }
}
我想要的价值是

[1,2,0,1,2,3,7,8,9,10]
编辑-我添加了最后一个大括号并修复了输出值

关于:

replace(x, is.na(x), (cumsum(is.na(x)) - 1)[is.na(x)])
你可以试试

f1 <- function(x){
   x1 <- is.na(x)
   rl <- rle(x1)
   x[x1] <- with(rl, sequence(lengths[values]))-1
 x}

f1(x)
# [1]  1  2  0  1  2  3  7  8  9 10

f1(xN)
# [1]  1  0  1  2  3  6  7  8  0  1  2  3  4  5  6 16 17 18 19 20

f1谢谢,第一个答案就是我要找的。这些值将用于插补缺失的值。
f1 <- function(x){
   x1 <- is.na(x)
   rl <- rle(x1)
   x[x1] <- with(rl, sequence(lengths[values]))-1
 x}

f1(x)
# [1]  1  2  0  1  2  3  7  8  9 10

f1(xN)
# [1]  1  0  1  2  3  6  7  8  0  1  2  3  4  5  6 16 17 18 19 20
indx <- is.na(xN)
xN[indx] <- seq_along(xN[indx])-1
xN
# [1]  1  0  1  2  3  6  7  8  4  5  6  7  8  9 10 16 17 18 19 20
x <-  c(1L, 2L, NA, NA, NA, NA, 7L, 8L, 9L, 10L)
xN <- c(1L, NA, NA, NA, NA, 6L, 7L, 8L, NA, NA, NA, NA, NA, NA, NA, 
    16L, 17L, 18L, 19L, 20L)