[R] Assignment converts variable to factor
ripley@stats.ox.ac.uk
ripley at stats.ox.ac.uk
Mon Jul 15 16:43:29 CEST 2002
This is intentional: use class "AsIs" to avoid the conversion,
If you had created the data frame as intended (using I()) this would have
worked.
Data frames are not designed to contain character columns.
For example,
dat <- data.frame(x=1:3, y = I(letters[1:3]))
dat[, "var2"] <- dat$x
is.factor(dat$var2) # FALSE
On Tue, 9 Jul 2002, Daniel Mastropietro wrote:
> Hello,
>
> I would like to know if this behaviour in R is as expected.
>
> I have a data frame 'dat' with column var1 being character (and not
> factor). Then I create a new column 'var2' by:
>
> > dat[,"var2"] <- dat$var1;
>
> Column var2 is now a factor.
>
> But if I do:
>
> > dat$var2 <- dat$var1;
>
> Then column var2 is character (and not factor).
>
> I don't want to have var2 as factor by doing the first assignment. I tried
> using 'as.character(dat$var1)' or converting dat[,"var2"] to character by
> using as.character() after the assignment, but still var2 is treated as factor.
>
> Note that I want to use dat[,"var2"] and not dat$var2 because I am doing
> the assignment within a function by referencing column var2 with a variable
> whose value is "var2" (e.g. dat[,col2] <- dat$var1, where col2 = "var2").
> It is easier and more clear to use the [] operator to reference a data
> frame column with a variable, rather than using the $ operator with the
> parse() function.
>
> Thanks
> Daniel Mastropietro
>
>
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
>
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272860 (secr)
Oxford OX1 3TG, UK Fax: +44 1865 272595
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list