Search code examples
rreplacedimensions

Can you explain how replace function is calculating vector length?


I am using replace function to replace numbers with characters in a list but seem to need to add an extra value to the index list for the code to work. (See example)

Simple version of by problem is that I have a list (0,1) and I want to replace 0 with "a" and 1 with "b".

replace(0:1, 0:1, c("a","b"))

Generates following results

[1] "a" "1"
Warning message:
In x[list] <- values :
  number of items to replace is not a multiple of replacement length

when extend index list to 0:2 I get the desired output

> replace(0:1, 0:2, c("a","b"))
[1] "a" "b"

I obviously don't understand how the replace function works but I can't seem to figure out what I am missing.


Solution

  • The second argument to replace is a list of indices (not values) and R uses 1-based indexing. 0:1 only contains 1 valid index. Thus in effect,

    replace(0:1, 0:1, c("a","b"))
    

    is equivalent to

    replace(0:1, 1, c("a","b"))
    

    which generates the warning message.

    It seems that you are really looking for the functionality of mapvalues from the plyr package. For example,

    x <- c(2,3,5,7,11)
    plyr::mapvalues(x,c(3,7),c(10,12))
    

    which leads to the output:

    [1]  2 10  5 12 11
    

    mapvalues is an example of a plyr function that doesn't have a direct analog in the newer package dplyr. See this question. Using both packages simultaneously is not recommended. This is why I used the more explicit plyr::mapvalues() rather than first library(plyr) and then simply mapvalues().