Read the help page for substr().
It says that the first argument should be a character vector.
The only one that works is the one where you gave it a character vector.
You said only third one "works". But you didn't explain what you
mean
by "works". It's always a good idea on r-help to show both what
you
expected, and what you actually got, so that people can understand
exactly what the question is.
To explain a little further, let me number your three approaches.
[1] substr(values,2,3) <- ".."
[2] substr(as.character(values),2,3) <- ".."
values <- as.character(values)
[3] substr(values,2,3) <- ".."
With regard to case [1]
It makes no sense to replace character substrings in a factor.
factors are really numbers, not characters. It's just that they have
additional attributes that make them (sometimes) print as if the were
characters. But they're not. And the error message (that you didn't
report) says exactly that.
With regard to case [2]:
values and as.character(values) are not the same thing.
Therefore, replacing substrings in as.character(values) is not the
same as replacing substrings in values. In this case, I would
interpret the error message to indicate that R is trying to replace
characters in a function. That makes sense, because you supplied a
function, namely, as.character().
Case [3] works because you supplied a character vector.
-Don
At 9:57 AM +0100 12/1/09, Antje wrote:>Hi there,
>
>I'm pretty sure that it's written down somewhere but I cannot find
it so far.
>
>The little example shows different approaches to replace a
>substring. Only the last one works. I think it has something to do
>with the fact that "substr" is used on the left side. Can anybody
>refer to an explanation for this behaviour?
>
>Thanks a lot in advance!
>
>Antje
>
>
>
>values <- factor(c(rep("abc",3), rep("bcd",3),
rep("cde",3)))
>
>substr(values,2,3) <- ".."
>substr(as.character(values),2,3) <- ".."
>
>values <- as.character(values)
>substr(values,2,3) <- ".."
>
>______________________________________________
>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.
--
---------------------------------
Don MacQueen
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062
macq at llnl.gov