[R] Substituting elements in vector

David Winsemius dwinsemius at comcast.net
Wed Feb 18 00:50:27 CET 2015


On Feb 17, 2015, at 3:58 AM, Knut Hansen 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")

> my.vlist <- setNames(as.list(my.vector),my.vector)
> replist <- list(B=vec1, E=vec2)
> my.vlist[c("B","E")] <- replist
> unlist(my.vlist)
  A  B1  B2  B3  B4  B5   C   D  E1  E2  E3   F   G 
"A" "p" "q" "r" "s" "t" "C" "D" "x" "y" "z" "F" "G" 

Could also have used:

my.vlist[ names(replist) ] <- replist

.... which I think illustrates the value of character indexing of lists for assignment even better.


> The ordering of the elements is important.
> 
> Knut Hansen
> 
> 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list