【问题标题】:How to replace multiple values at once [duplicate]如何一次替换多个值[重复]
【发布时间】:2018-06-17 16:45:50
【问题描述】:

我想一次用特定的其他值替换向量中的不同值。

在我正在解决的问题中:

  • 1 应该换成 2,
  • 2 与 4,
  • 3 加 6,
  • 4 加 8,
  • 5 加 1,
  • 6 与 3,
  • 7 和 5 和
  • 8 和 7。

这样:

x <- c(4, 2, 0, 7, 5, 7, 8, 9)
x
[1] 4 2 0 7 5 7 8 9

将转换为:

[1] 8 4 0 5 1 5 7 9

替换后。

我尝试过使用:

x[x == 1] <- 2
x[x == 2] <- 4

以此类推,但这会导致 1 被 7 替换。

不使用任何包的最简单的解决方案是什么?

【问题讨论】:

  • 限于个位数,但很有趣:type.convert(strsplit(chartr(paste(1:8, collapse = ''), paste(c(2, 4, 6, 8, 1, 3, 5, 7), collapse = ''), paste(x, collapse = '')), '')[[1]])
  • 参见例如the accepted answer in the first link 中的“更通用的方法”。
  • second link 中的“索引命名向量”方法在您的情况下为 setNames(c(0,2,4,6,8,1,3,5,7,9), 0:9)[as.character(x)]

标签: r


【解决方案1】:

使用match的可能解决方案:

old <- 1:8
new <- c(2,4,6,8,1,3,5,7)

x[x %in% old] <- new[match(x, old, nomatch = 0)]

给出:

> x
[1] 8 4 0 5 1 5 7 9

这是做什么的:

  • 创建两个向量:old 带有需要替换的值,new 带有相应的替换。
  • 使用match 查看x 中的值出现在old 中的什么位置。使用nomatch = 0 删除NA。这会为x 值生成old 中位置的索引向量
  • 此索引向量可用于索引new
  • 仅将来自new 的值分配给xold 中存在的位置:x[x %in% old]

【讨论】:

【解决方案2】:

如果可以为所有值定义转换对,则可以选择转换为factor,然后再转换回整数。

old <- 0:9
new <- c(0,2,4,6,8,1,3,5,7,9)

as.integer(as.character(factor(x, old, new)))
# [1] 8 4 0 5 1 5 7 9

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 2023-03-17
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 2011-10-22
    • 1970-01-01
    相关资源
    最近更新 更多