On 11/06/11 18:14, jour4life wrote:
That's great! But, I guess I should have provided a better example for
my problem. The reason being that I did not consider strings. For
instance, in my case, I'm actually trying to add a value to a data frame
that looks like this:

Obs     X
0     NA
1     "01 001"
2     "01 002"
3     "01 003"

And I am actually trying to get that specific "NA" value and convert it
to "00 000" so it can look like this:

Obs     X
0     "00 000"
1     "01 001"
2     "01 002"
3     "01 003"

When I write the code you provided, I get this result:

x[1,"X"]<-"00 000"
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = c(NA, 3L, 4L, 5L, 6L, 7L,  :

invalid factor level, NAs generated

I am wondering what I am doing wrong and how to solve this problem.

Thanks for all the help!

The error is clear enough, isn't it? "00 000" is not one of the levels of the
"X" column of your data frame; this column is a factor.  Probably because
of the "stringsAsFactors = TRUE" default in options().

Since you appear to have been unaware of the factor nature of "X", presumably
you don't really want it to be a factor.  If this is the case execute

    x[,"X"] <- as.character(x[,"X"])

and then your reassignment of the [1,"X"] entry of "x" will work.

If you do want "X" to be a factor you could:

(a) execute x[,"X"] <- factor(x[,"X"]) *after* doing the reassignment, or

(b) execute levels(x[,"X"]) <- c("00 000",levels(x[,"X"])) *before* doing
    the reassignment.

Learn more about how R works.  In particular learn about factors; they are
important and useful.

    cheers,

        Rolf Turner

______________________________________________
R-help@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.

Reply via email to