[R] matrix logic

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Jan 11 09:15:23 CET 2006


The equality operator is == not =.  So you need is.na(data1) == FALSE (F 
is a variable, and FALSE is the non-truth value), or, clearer,

ifelse(!is.na(data1), data1, data2)

Another way is

data3 <- data1
data3[is.na(data1)] <- data2[is.na(data1)]

which is more efficient but less clear.

On Tue, 10 Jan 2006, r user wrote:

> I have 2 dataframes, each with 5 columns and 20 rows.
> They are called data1 and data2.I wish to create a
> third dataframe called data3, also with 5 columns and
> 20 rows.
>
> I want data3 to contains the values in data1 when the
> value in data1 is not NA.  Otherwise it should contain
> the values in data2.
>
> I have tried afew methids, but they do not seem to
> work as intended.:
>
> data3<-ifelse(is.na(data1)=F,data1,data2)
>
> and
>
> data3[,]<-ifelse(is.na(data1[,])=F,data1[,],data2[,])
>
> Please suggest the “best” way.

-- 
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