2015-12-11 53 views
1

比方說,我有一個載體我們如何替換R中向量中的元素?

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') 

我怎麼能做到這一點,而不使用循環在我的第一個向量的每個元素?

回答

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" 
+0

感謝這個答案。我們如何以自動化的方式做到這一點?我提供的例子是我的例子的簡化版本,我有40個不同的值。所以我正在尋找一種不需要鍵入40個鍵值對的方法。 –

1

爲此我使用簡單recode功能。作爲輸入你需要矢量被改變表示爲x,值的向量是變化from和更換的一矢量值to(所以from[1]被重新編碼爲to[1]),可以指定other值和所有不在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) 
3

可以使用match功能:

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