[R] subbing a string vector for another string vector

Phil Spector spector at stat.berkeley.edu
Thu Sep 9 00:03:34 CEST 2010


One way to do it is with mapply:

> mydf = data.frame(image=c('http://$IMAGE_ID$','$IMAGE_ID$'),pattern=c('www.url.com/image.jpg','http://www.blah.com/image.gif'))
> mydf$url  = mapply(sub,"\\$IMAGE_ID\\$",mydf$pattern,mydf$image)
> mydf
               image                       pattern                           url
1 http://$IMAGE_ID$         www.url.com/image.jpg  http://www.url.com/image.jpg
2        $IMAGE_ID$ http://www.blah.com/image.gif http://www.blah.com/image.gif

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu




On Wed, 8 Sep 2010, jlemaitre wrote:

>
> I have a data frame with two columns:
>      image                               pattern
> 1    http://$IMAGE_ID$            www.url.com/image.jpg
> 2    $IMAGE_ID$                      http://www.blah.com/image.gif
> ...
>
> I want to replace "$IMAGE_ID$" with the corresponding entry in the pattern
> column such that the result would appear as follows:
>
> url
> http://www.url.com/image.jpg
> http://www.blah.com/image.gif
>
> Using something like  > gsub("\\$IMAGE\\_ID\\$",image,pattern) doesn't work
> because it only takes uses the first entry in "pattern" as the replacement
> for all "image" entries:
>
> url
> http://www.url.com/image.jpg
> www.url.com/image.jpg
>
> Please help.
> Thanks.
>
>
>
>
> -- 
> View this message in context: http://r.789695.n4.nabble.com/subbing-a-string-vector-for-another-string-vector-tp2532005p2532005.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list