【问题标题】:How can we replace elements in a vector in R?我们如何替换 R 中向量中的元素?
【发布时间】:2015-12-11 09:45:52
【问题描述】:

比方说,我有一个向量

animal <- c('cat','snake','cat','pigeon','snake')

还有一个名为

的数据框
map <- data.frame(find=c('cat','snake','pigeon'),replace=c('mammal','reptile','bird')

现在我希望通过将动物的每个元素与地图的替换列匹配来使用地图修改动物。所以我期待:

animal <- c('mammal','reptile','mammal','bird','reptile')

如何在第一个向量的每个元素上不使用循环的情况下做到这一点?

【问题讨论】:

    标签: r


    【解决方案1】:

    你可以使用match函数:

    > animal <- as.character(map[match(animal, map$find), "replace"])
    > animal
    [1] "mammal"  "reptile" "mammal"  "bird"    "reptile"
    

    【讨论】:

      【解决方案2】:

      您可以将animal 视为一个因素并重命名其级别。 例如,使用plyr 包:

      library(plyr)
      animal <- c('cat','snake','cat','pigeon','snake')
      animal2 <- revalue(animal, c("cat" = "mammal", 
                                   "snake" = "reptile", 
                                   "pigeon" = "bird"))
      
      > animal
      [1] "cat"    "snake"  "cat"    "pigeon" "snake" 
      > animal2
      [1] "mammal"  "reptile" "mammal"  "bird"    "reptile"
      

      按照下面评论中的要求使其自动化

      repl <- as.character(map$replace)
      names(repl) <- map$find
      animal2 <- revalue(animal, repl)
      
      > animal
      [1] "cat"    "snake"  "cat"    "pigeon" "snake" 
      > animal2
      [1] "mammal"  "reptile" "mammal"  "bird"    "reptile"
      

      【讨论】:

      • 感谢您的回答。我们如何以自动化的方式做到这一点?我提供的示例是我的案例的简化版本,其中有 40 个不同的值。所以我正在寻找一种不需要键入 40 个键值对的方法。
      【解决方案3】:

      为此,我使用简单的recode 函数。作为输入,您需要更改向量,表示为x,要更改的值向量from 和替换值向量to(因此from[1] 被重新编码为to[1]),您可以指定@987654327 @value 和所有不在from 中的值将被重新编码为other。您可以在下面找到粘贴的函数。

      recode <- function(x, from, to, other) {
        stopifnot(length(from) == length(to))
      
        new_x <- x
        k <- length(from)
        for (i in 1:k) new_x[x == from[i]] <- to[i]
      
        if (!missing(other) && length(other) > 1) {
          new_x[!(x %in% from)] <- other[1]
          warning("'other' has length > 1 and only the first element will be used")
        }
      
        new_x
      }
      

      使用您自己的示例,用法将是

      recode(animal, map$find, map$replace)
      

      【讨论】:

        最近更新 更多