[R] replacement in a dataframe

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Oct 26 09:49:45 CEST 2005


On Wed, 26 Oct 2005, Marco Venanzi wrote:

> Hi,I want to replace some elements of a dataframe "a"J, using 2 index 
vectors ("x" and "y") and a vector of replacement ("z") of the same length 
of "x" and "y".
> I've tried a[cbind(x,y)]<-z, but it doesn't work.How can I do it in a 
> simply way?Thanks,

Only logical matrix indexing is supported for data frames: See 
?"[.data.frame".  So you need to create a logical matrix index. One way 
would be

aa <- is.na(a) # create a logical matrix of the same size
aa[] <- FALSE
aa[cbind(x,y)] <- TRUE
a[aa] <- z

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