Bliese, Paul D MAJ WRAIR-Wash DC
2003-Feb-01 18:29 UTC
[R] matrix subscripts in replacement
I'm reluctant to draw the S-PLUS and R comparison (these are different programs after all), but could someone tell me why the following matrix substitution works in S-PLUS, but not R. I'm curious because matrix substitution is a really slick way to "cleaning up" columns of data in data frames. For example, in the following I change values of 1 to values of 10, but only for columns 1 and 3. # S-PLUS example below> TEMP<-data.frame(VAR1=c(1,2,3,4,5),VAR2=c(5,4,3,2,1),VAR3=c(1,1,1,1,NA)) > TEMPVAR1 VAR2 VAR3 1 1 5 1 2 2 4 1 3 3 3 1 4 4 2 1 5 5 1 NA> TEMP[,c(1,3)][TEMP[,c(1,3)]==1&!is.na(TEMP[,c(1,3)])]<-10 > TEMPVAR1 VAR2 VAR3 1 10 5 10 2 2 4 10 3 3 3 10 4 4 2 10 5 5 1 NA # R Example Below (version 1.6.1 Windows)> TEMP<-data.frame(VAR1=c(1,2,3,4,5),VAR2=c(5,4,3,2,1),VAR3=c(1,1,1,1,NA)) > TEMPVAR1 VAR2 VAR3 1 1 5 1 2 2 4 1 3 3 3 1 4 4 2 1 5 5 1 NA> TEMP[,c(1,3)][TEMP[,c(1,3)]==1&!is.na(TEMP[,c(1,3)])]<-10Error in "[<-.data.frame"(*tmp*, TEMP[, c(1, 3)] == 1 & !is.na(TEMP[, : matrix subscripts not allowed in replacement Thanks! Paul Bliese Walter Reed Army Institute of Research
ripley@stats.ox.ac.uk
2003-Feb-01 18:57 UTC
[R] matrix subscripts in replacement (in a data frame)
Simple: it's not been implemented in R. Would you like to contribute an implementation? Remember, R is a volunteer project and what gets implemented depends on the volunteer's needs. On Sat, 1 Feb 2003, Bliese, Paul D MAJ WRAIR-Wash DC wrote:> I'm reluctant to draw the S-PLUS and R comparison (these are different > programs after all), but could someone tell me why the following matrix > substitution works in S-PLUS, but not R. I'm curious because matrix > substitution is a really slick way to "cleaning up" columns of data in data > frames. For example, in the following I change values of 1 to values of 10, > but only for columns 1 and 3. > > # S-PLUS example below > > > TEMP<-data.frame(VAR1=c(1,2,3,4,5),VAR2=c(5,4,3,2,1),VAR3=c(1,1,1,1,NA)) > > TEMP > VAR1 VAR2 VAR3 > 1 1 5 1 > 2 2 4 1 > 3 3 3 1 > 4 4 2 1 > 5 5 1 NA > > TEMP[,c(1,3)][TEMP[,c(1,3)]==1&!is.na(TEMP[,c(1,3)])]<-10 > > TEMP > VAR1 VAR2 VAR3 > 1 10 5 10 > 2 2 4 10 > 3 3 3 10 > 4 4 2 10 > 5 5 1 NA > > # R Example Below (version 1.6.1 Windows) > > > TEMP<-data.frame(VAR1=c(1,2,3,4,5),VAR2=c(5,4,3,2,1),VAR3=c(1,1,1,1,NA)) > > TEMP > VAR1 VAR2 VAR3 > 1 1 5 1 > 2 2 4 1 > 3 3 3 1 > 4 4 2 1 > 5 5 1 NA > > TEMP[,c(1,3)][TEMP[,c(1,3)]==1&!is.na(TEMP[,c(1,3)])]<-10 > Error in "[<-.data.frame"(*tmp*, TEMP[, c(1, 3)] == 1 & !is.na(TEMP[, : > matrix subscripts not allowed in replacement-- 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