当存在定义的差异时替换向量之间的值

Replacing the value in between vectors when there is a defined difference

我对替换向量之间的值有疑问。

算法应该在满足特定条件时找到替换编号。在这种情况下,找到与前一个数字相差 -20 的数字。所以我更喜欢使用diff函数。

这就是我的意思

x <- c(20,20,0,20,0,5)
> diff(x)
[1]   0 -20  20 -20   5

所以在这种情况下 0 产生 -20,我想将那些 0 更改为 20。 .我知道最简单的解决方案是直接分配 x[3] <- 20x[5] <- 20

但是,0 位置总是不同的,所以我需要一个可以做到这一点的自动化流程。谢谢!

**编辑 如果我们需要在分组 data.frame

中执行此操作
> df
    x gr
1  20  1
2  20  1
3   0  1
4  20  1
5   0  1
6   5  1
7  33  2
8   0  2
9  20  2
10  0  2
11 20  2
12  0  2

我们如何实施?

modify <- function(x){
  value_search = c(0, 33)
  value_replacement = c(20, 44)

  for (k in 1:length(value_search)) {
  index_position = which(x %in% value_search[k])
  replacement = value_replacement[k]
  for (i in index_position) {
    x[i] = replacement
  }
  }
}


df%>%
  group_by(gr)%>%
  mutate(modif_x=modify(x))

Error in mutate_impl(.data, dots) : 
  Evaluation error: 'match' requires vector arguments.

您可以使用 which 来获取位置,即

x[which(diff(x) == -20)+1] <- 20
x
#[1] 20 20 20 20 20  5

如果您想要一种通用的方法来根据特定值替换向量的值,我会采用这种方法。

x = c(20,20,0,20,0,5)
value_search = 0
value_replacement = 20

index_position = which(x %in% value_search)
for (i in index_position) {
  x[i] = value_replacement
}

但这适用于单个值。如果要查找多个值,可以使用如下嵌套循环:

x = c(20,20,0,20,0,5,33)
value_search = c(0, 33)
value_replacement = c(20, 44)

for (k in 1:length(value_search)) {
  index_position = which(x %in% value_search[k])
  replacement = value_replacement[k]
  for (i in index_position) {
    x[i] = replacement
  }
}

回应 OP 的编辑: 任意数量的方法来做到这一点:

x = c(20,20,0,20,0,5,33)
gr = c(1,1,1,1,2,2,2)
df = data.frame(x, gr)

func_replace <- function(source, value_search, value_replacement) {
  for (k in 1:length(source)) {
    index_position = which(x %in% value_search[k])
    replacement = value_replacement[k]
    for (i in index_position) {
      source[i] = replacement
    } # for i loop
  } # for k loop
  return(source)
} # func_replace

value_search = c(0, 33)
value_replacement = c(20, 44)
gr_value = 1

df$replacement = with(df, ifelse(gr == gr_value, sapply(df, FUN = function(x) func_replace(x, value_search, value_replacement)), NA))