[R] how to checking whether elements of a vector changed or not.

David Winsemius dwinsemius at comcast.net
Tue Jun 2 22:32:46 CEST 2009


Gabor;

Did you perhaps get an undesired doubling of "!"?

 > x1 <-c("A", "A", "B", "B", "B", "A")
 > x1[2:length(x1)] == x1[1:(length(x1)-1)]
[1]  TRUE FALSE  TRUE  TRUE FALSE

 > !!diff(c(factor(x1)))
[1] FALSE  TRUE FALSE FALSE  TRUE

(Your trick of computing differences of the underlying factor  
representation ... ganz raffiniert.)

-- 
David Winsemius

On Jun 1, 2009, at 6:21 PM, Gabor Grothendieck wrote:

> Try this:
>
> c(FALSE, !!diff(c(factor(x))))
>
>
> On Mon, Jun 1, 2009 at 11:57 AM, liujb <liujulia7 at yahoo.com> wrote:
>>
>> Hello,
>>
>> I have a vector:
>> x <- c("A", "A", "A", "B", "A", "A", "C")
>>
>> I'd like to compare each of elements of vector x from its previous  
>> element
>> (except for the 1st element which does not have previous element).  
>> So I'd
>> like to get a vector y (of same length) that looks something like
>> (0, 0, 0, 1, 1, 0, 1) or
>> (F, F, F, T, T, F, T)
>>
>> Is there a command that do this?
>>
>> I was thinking to construct another variable x1 from x as follows:
>> x1 <- vector(length=length(x))
>> x1[1] <- x[1]
>> x1[2:length(x)] <- x[1:(length(x)-1)]
>> x1
>>
>> Now, x1 is ("A" "A" "B" "B" "B" "A"). However, I don't know how to  
>> compare 2
>> vectors (of same length) elements by elements and a vector that  
>> indicates
>> change or no change.
>>
>> Or there is a easier way to do this?
>>
>> Thank you very much
>> Julia
>>

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list