[R] Substituting elements in vector

Berend Hasselman bhh at xs4all.nl
Tue Feb 17 19:28:46 CET 2015


> On 17-02-2015, at 12:58, Knut Hansen <knut.hansen at uit.no> wrote:
> 
> Dear list,
> 
> I have a vector:
> my.vector <- c("A", "B", "C", "D", "E", "F", "G")
> 
> and two other:
> vec1 <- c("p", "q", "r", "s", "t")
> vec2 <- c("x", "y", "z")
> 
> I want to substitute elements "b" and "e" in my.vector with vectors vec1 and 
> vec2 respectively so that the result becomes the vector:
> c("A", "p", "q", "r" , "s" , "t", "C" , "D", "x", "y", "z", "F", "G")
> 
> The ordering of the elements is important.
> 

Something like this perhaps

res <- c("A", "p", "q", "r" , "s" , "t", "C" , "D", "x", "y", "z", "F", "G”)

rem <- function(vec, who, replace){
	kW <- which(vec == who)
	z1 <- append(vec,replace,kW)
	z2 <- z1[ ! z1 %in% vec[kW] ]
	z2
}

x1 <- rem(my.vector,"B",vec1)
x2 <- rem(x1,"E",vec2)
x2
all.equal(x2,res)

Berend



More information about the R-help mailing list