Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.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,我使用的是数据表,有一列包含数字或NA。从第1行开始,我想通过添加最小行数对列求和,直到满足或超过特定值,或者遇到NA。然后应该在第2行重新开始,每行重复一次。一旦它通过了一个NA作为新的起始位置,它就可以继续到下一个NA 如果两个目标均未达到,则返回值应为sum或NA 数字的范围可以是任何数字,但大多是-1、0和1 我已经写了一个函数,但它的速度超过了400万行。有没有办法让我做得更快?我想改变PosMax和NegMax变量 谢谢你的帮助 z <- c(1, 1, NA, 2, -1,

我使用的是数据表,有一列包含数字或NA。从第1行开始,我想通过添加最小行数对列求和,直到满足或超过特定值,或者遇到NA。然后应该在第2行重新开始,每行重复一次。一旦它通过了一个NA作为新的起始位置,它就可以继续到下一个NA

如果两个目标均未达到,则返回值应为sum或NA

数字的范围可以是任何数字,但大多是-1、0和1

我已经写了一个函数,但它的速度超过了400万行。有没有办法让我做得更快?我想改变PosMax和NegMax变量

谢谢你的帮助

z <- c(1, 1, NA, 2, -1, 0, 0, 0, -1, 1 ,1, -1, 0 ,0 ,0, 1)
FindMovement(z, 2, -1)
  [1]  2 NA NA  2 -1 NA NA NA -1  2 NA -1 NA NA NA NA

试试这个,现在无法测试性能,但应该更快:

z.mat <- matrix(rep(z, length(z)), ncol=length(z))
# zero out prior values for each col
z.mat[upper.tri(z.mat)] <- 0
# get a cumsum of each column
z.mat.sum <- apply(z.mat, 2, cumsum)
# add condition that if series starts with 0, should be NA
diag(z.mat.sum)[diag(z.mat.sum) == 0] <- NA
# get the first of -1, 2, or NA in the cumsum
result <- apply(z.mat.sum, 2, function(x) x[which.max(x %in% c(-1, 2, NA))])
# for columns that didn't get to a target, you'll get 0, so replace these with NA
result[result == 0] <- NA
result
# [1]  2 NA NA  2 -1 NA NA NA -1  2 NA -1 NA NA NA NA

z.mat第一段我已经读了好几遍了,我看不出该描述与您的
FindMovement
函数的输出如何匹配。请编辑您的问题,让我们了解它是如何工作的。用c语言重新编写该函数并使用
内联
程序包运行它并不困难。Hanks工作得很好(尽管我移动了目标栏)但是当我尝试将它应用于一组400万个数字时,它的内存不足。您可以在
NA
s处拆分向量,分别处理每个部分,然后合并结果。
Position  1:  1 + 1 = 2 (PosMax)
Position  2:  1 + NA = NA
Position  3:  NA = NA
Position  4:  2 = 2
Position  5: -1 = -1 (NegMax)
Position  6:  0 = NA 
Position  7:  0 = NA
Position  8:  0 = NA
Position  9: -1 = -1
Position 10:  1 + 1 = 2
Position 11:  1 + -1 + 0 + 0 + 0 + 1 = NA (Target not reached)
Position 12: -1 = -1
Position 13:  0 = NA
Position 14:  0 = NA
Position 15:  0 = NA
Position 16:  1 = NA
z.mat <- matrix(rep(z, length(z)), ncol=length(z))
# zero out prior values for each col
z.mat[upper.tri(z.mat)] <- 0
# get a cumsum of each column
z.mat.sum <- apply(z.mat, 2, cumsum)
# add condition that if series starts with 0, should be NA
diag(z.mat.sum)[diag(z.mat.sum) == 0] <- NA
# get the first of -1, 2, or NA in the cumsum
result <- apply(z.mat.sum, 2, function(x) x[which.max(x %in% c(-1, 2, NA))])
# for columns that didn't get to a target, you'll get 0, so replace these with NA
result[result == 0] <- NA
result
# [1]  2 NA NA  2 -1 NA NA NA -1  2 NA -1 NA NA NA NA