R 根据除法结果将向量除以不同的值

R 根据除法结果将向量除以不同的值,r,R,我有这样一个Df: x y z <dbl> <dbl> <dbl> 1 408001.9 343 0 2 407919.2 343 0 3 407839.6 343 0 4 407761.2 343 0 5 407681.7 343

我有这样一个Df:

          x         y          z
  <dbl>     <dbl>      <dbl>
1  408001.9       343          0
2  407919.2       343          0
3  407839.6       343          0
4  407761.2       343          0
5  407681.7       343          0
6  407599.0       343          0
7  407511.0       343          0
8  407420.5       343          0
9  407331.0       343          0
10 407242.0       343          0
11 407152.7       343          0
12 407062.5       343          0
13 406970.7       343          0
14 406876.6       342          0
15 406777.1       342          0
16 406671.0       342          0
17 406560.9       342          0
18 406449.4       342          0
19 406339.0       342          0
20 406232.5       342          0
...  ...          ...         ...
a1 现在我想用
df$x
除以
vec[1]
,得到与
df$y
相同的结果(四舍五入)

但是现在,当
df$z
中的值下降1到342时,我想将
df$x
中的值除以
vec[2]
从那时起,得到新的
df$z

从这里开始,结果将不同于
df$y
,因为
df$y
要除以的数字始终是
vec[1]
,并且不会改变

每当我得到的
df$z
的值下降一次时,
df$z
的下一个值将使用相应的
vec[I]
计算,其中I是到目前为止的下降次数+1

最后我想要一个向量
df$z
,其中的值是
df$x/vec[I]
,其中
vec[I]
取决于
df$z
的最后一个数字是多少

可复制示例:

test <- data.frame(x = sort((seq(500, 600, 2)), decreasing = T)
                   )

vec <- seq(10, 10.9, 0.03)

for(i in 1:31){
  test[i+1] <- round(test$x/vec[i])
}

test我希望我理解了你的要求。也许就是这个

test <- data.frame(x = sort((seq(500, 600, 2)), decreasing = T)
vec <- seq(10, 10.9, 0.03)

#this function determines the index of `vec` to use
xcol<-function(v){
  x<-rep(NA,length(v))
  x[1] <- 1
  for(i in 2:length(v)){
    x[i] <- x[i-1]
    if(round(v[i]/vec[x[i]])<round(v[i-1]/vec[x[i]])){
      x[i] <- x[i]+1
    }
  }
  return(x)
}

test$xcol <- xcol(test$x)
test$z <- round(test$x/vec[test$xcol])

 test
     x xcol  z
1  600    1 60
2  598    1 60
3  596    1 60
4  594    2 59
5  592    2 59
6  590    2 59
7  588    2 59
8  586    3 58
9  584    3 58
10 582    3 58
11 580    3 58
12 578    4 57
...

测试井,直到第一次下降。从那时起,df$y和df$z的下降将在不同的位置。随着vec中的值不断增加,df$z中的下降将早于df$yIt中的下降。如果您可以扩展您的问题,以说明这是如何工作的,因为这并不清楚。正确答案应该是什么样的?我在问题中添加了一些信息。希望它更明显,我现在需要的。
test <- data.frame(x = sort((seq(500, 600, 2)), decreasing = T)
vec <- seq(10, 10.9, 0.03)

#this function determines the index of `vec` to use
xcol<-function(v){
  x<-rep(NA,length(v))
  x[1] <- 1
  for(i in 2:length(v)){
    x[i] <- x[i-1]
    if(round(v[i]/vec[x[i]])<round(v[i-1]/vec[x[i]])){
      x[i] <- x[i]+1
    }
  }
  return(x)
}

test$xcol <- xcol(test$x)
test$z <- round(test$x/vec[test$xcol])

 test
     x xcol  z
1  600    1 60
2  598    1 60
3  596    1 60
4  594    2 59
5  592    2 59
6  590    2 59
7  588    2 59
8  586    3 58
9  584    3 58
10 582    3 58
11 580    3 58
12 578    4 57
...