[R] replace NA with factor class

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Thu Jan 2 14:50:03 CET 2003


On Thu, 2 Jan 2003, Tord Snall wrote:

> I have a tree data matrix.

Don't think so: you appear to have a data frame, which is not at all the
same thing.

> For some trees I lack info about tree species,
> but I want to set them to be spruce. For some reason the tree species names
> on the remaining (non-NA) rows are changed into numbers (that I do not
> recognise).

You should do so.  They are the code of the factor in your data frame.

> I guess that ifelse is not the correct function to use, but I have not
> found any better one in my searches.

Your two arguments to ifelse are a character vector and a factor. You
will get coercion of the factor to an atomic type, and that's where the
codes come from.


test$tree.sp[is.na(test$tree.sp)] <- "spruce"

is probably what you wanted.

>
> Thanks in advance!
>
> Sincerely,
> Tord
>
>
> > test
>       ObjektID tree.sp Diameter
> 2030 S.2001.S5    <NA>        2
> 2034 S.2001.S5    <NA>        2
> 1          S.1   spruce       2
> 2          S.1    birch      12
> 3          S.1   spruce       7
> 4          S.1   spruce       5
> 5          S.1    birch       8
>
> > test$tree.sp6<- ifelse(is.na(test$tree.sp) == T, "spruce", test$tree.sp)
>
> > test
>       ObjektID tree.sp Diameter tree.sp6
> 2030 S.2001.S5     <NA>        2      spruce
> 2034 S.2001.S5     <NA>        2      spruce
> 1          S.1   spruce        2         8
> 2          S.1    birch       12         3
> 3          S.1   spruce        7         8
> 4          S.1   spruce        5         8
> 5          S.1    birch        8         3
>
>
> -----------------------------------------------------------------------
> Tord Snäll
> Avd. f växtekologi, Evolutionsbiologiskt centrum, Uppsala universitet
> Dept. of Plant Ecology, Evolutionary Biology Centre, Uppsala University
> Villavägen 14
> SE-752 36 Uppsala, Sweden
> Tel: 018-471 28 82 (int +46 18 471 28 82) (work)
> Tel: 018-25 71 33 (int +46 18 25 71 33) (home)
> Fax: 018-55 34 19 (int +46 18 55 34 19) (work)
> E-mail: Tord.Snall at ebc.uu.se
> Check this: http://www.vaxtbio.uu.se/resfold/snall.htm!
> ------------------------------------------------------------------------
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help
>

-- 
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 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list