[R] Compare two subsequent rows based on specific values of a string

arun smartpink111 at yahoo.com
Fri Sep 20 18:11:02 CEST 2013


Hi,
May be this helps:
dat1<- read.table(text="x1    x2    x3   x4  
1     xz   ab    cd    ef
2     ab   fz    cd    ef
3     ab   cd   dy    dx",sep="",header=TRUE,stringsAsFactors=FALSE)
dat1$changes_to_row_above<- sapply(seq_len(nrow(dat1)),function(i) {x1<-dat1[,i]%in% dat1[,i-1];if(any(x1)) sum(x1,na.rm=TRUE) else NA})
 dat1
#  x1 x2 x3 x4 changes_to_row_above
#1 xz ab cd ef                   NA
#2 ab fz cd ef                    1
#3 ab cd dy dx                    2

A.K.



Dear all, 

I would like to compare two rows and check whether something 
changed. The only thing is, it is not always the same column that needs 
to be compared. It is rather a matrix of values. The outcome would be a 
number of changes in these, for instance: "of row 2, there are 3 exactly
 same values in row 3". I will make up an example: 

      x1    x2    x3   x4   changes_to_row_above 
1     xz   ab    cd    ef   NA 
2     ab   fz    cd    ef   1 
3     ab   cd   dy    dx   2 
and so forth... 

Do you think that would be possible? Is there an easy function 
to do so? It would be great help guys, thanks a lot in advance, sorry 
for my bad data manipulation knowledge... 

Tobi



More information about the R-help mailing list