Skip to content
Prev 301816 / 398506 Next

replace values in vector from a replacement table

On Mon, Jul 30, 2012 at 6:00 PM, jim holtman <jholtman at gmail.com> wrote:
Based on this code I came up with the following function.

replace2 <- function(x, ind, repl){
    if(any(is.na(ind))) ind[is.na(ind)] <- 0
    if(is.vector(x) & is.vector(repl)) {
        (x[ind != 0] <- repl[ind])
        return(x)
    } else if(identical(ncol(x), ncol(repl))){
        (x[ind != 0, ] <- repl[ind, ])
        return(x)
    }
}

Whereas replicate() can be used only on vectors of same dimension,
replicate2() can be used on vectors and matrices/dataframes, and the
replacement data can have different nr of rows.  It also works with
index vectors containing NAs.
[1] 2 3 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 0 5 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
[46] 0 0 0 0 0 0 0
[1] "A" "B" "c" "D" "e" "f"
[1]  2  3 NA  5 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
NA NA NA NA  2  3 NA  5
[31] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[1] "A" "B" "c" "D" "e" "f"
x   x
[1,] "a" "a"
[2,] "b" "b"
[3,] "c" "c"
[4,] "d" "d"
[5,] "e" "e"
[6,] "f" "f"
[,1] [,2]
[1,] "aa" "aa"
[2,] "A"  "A"
[3,] "B"  "B"
[4,] NA   NA
[5,] "D"  "D"
[6,] "zz" "zz"
x   x
[1,] "A" "A"
[2,] "B" "B"
[3,] "c" "c"
[4,] "D" "D"
[5,] "e" "e"
[6,] "f" "f"


Does this function have any generic value? Are there obvious
implementation mistakes?

Regards
Liviu