Skip to content
Prev 167334 / 398502 Next

changing a range of values

> x[x %in% 1:3]
[1] 1 1 1 2 2 3

So ...
 > x[x %in% 1:3] <- 1

 > x
[1] 1 1 1 1 1 1 4 4 5
On Jan 17, 2009, at 12:03 PM, J?rg Gro? wrote:

            
It appears to be the result of with argument recycling. If you change  
the problem to one where the length of x is not a multiple of the  
other side of the equality, you get a warning that is typical for that  
sort of problem:

 > x <- c(1,1,1,2,2,3,3,3,4,4,5)
 >
 >
 >
 > x[x == c(1:3)]
[1] 1 2 3
Warning message:
In x == c(1:3) :
   longer object length is not a multiple of shorter object length

 > x[x == c(1:3)] <- c(1)
Warning message:
In x == c(1:3) :
   longer object length is not a multiple of shorter object length
 >
 > x
  [1] 1 1 1 2 1 1 3 3 4 4 5

I think it is testing these equalities with the matches having a up- 
caret.
  1 1 1 2 2 3 3 3 4 4 5
  1 2 3 1 2 3 1 2 3 1 2
        ^   ^