[R] matrix subscripts in replacement

Bliese, Paul D MAJ WRAIR-Wash DC Paul.Bliese at NA.AMEDD.ARMY.MIL
Sat Feb 1 18:29:02 CET 2003


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


Thanks!

Paul Bliese
Walter Reed Army Institute of Research




More information about the R-help mailing list