[R] a replacement problem
Marc Schwartz
MSchwartz at medanalytics.com
Sat Mar 13 03:38:26 CET 2004
On Fri, 2004-03-12 at 19:37, Yong Wang wrote:
> hi,all
> a quick question:
>
> a vector
>
> v<-c(g,r,y,g,y,y,r)
>
> needs to be
>
> v<-c(1,2,3,1,3,3,2)
>
> i.e., replace g,r,y as 1,2,3
A couple of options and probably more:
1. Using a loop and a quick function I wrote called "gsr" (for Global
Search and Replace):
gsr <- function(Source, Search, Replace)
{
for (i in 1:length(Search))
{
Source <- replace(Source, Source == Search[i], Replace[i])
}
Source
}
v <- c("g", "r", "y", "g", "y", "y", "r")
gsr(v, c("g", "r", "y"), 1:3)
[1] "1" "2" "3" "1" "3" "3" "2"
Note the above returns character values, so if you want numerics:
> as.numeric(gsr(v, c("g", "r", "y"), 1:3))
[1] 1 2 3 1 3 3 2
Also, in the above function, you would want to be sure that both Search
and Replace are vectors of equal length and could add some error
checking code for that prior to the for() loop:
if (length(Search) != length(Replace))
stop("Search and Replace Must Have Equal Number of Items\n")
2. Using a "trick" with unclass() and factor():
> as.vector(unclass(factor(v, levels = c("g", "r", "y"))))
[1] 1 2 3 1 3 3 2
> how to do that, by the way, what key words I should use to search for such
> basic operation command?
Strangely enough:
help.search("replace")
;-)
See ?replace for more info and there is also the grep family for complex
search and replace operations based on regex. See ?grep.
HTH,
Marc Schwartz
More information about the R-help
mailing list