[R] Substituting elements in vector
Knut Hansen
knut.hansen at uit.no
Wed Feb 18 14:01:33 CET 2015
Tirsdag 17. februar 2015 15.50.27 skrev David Winsemius:
> 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
Thank you. This was what I was looking for. I was not aware of named lists in
R, and I was about to write a script in Python to fix this.
Knut Hansen
More information about the R-help
mailing list