jeudi 18 avril 2019

String comparison in 2 adjacent rows of a data frame in R

I have a data-frame with 627 observations and 16 variables are present. I am considering one column named "ZoneDivison" which has factors: North Eastern, Eastern and South Eastern. So, I want to compare the adjacent row values and create a new column which has 1, if two adjacent rows have same zones, else 0, if the adjacent rows are different.

I referred to the following links to find a way out: [here] Matching two Columns in R [here] compare row values over multiple rows (R)

library(dplyr)
a <- c(rep("Eastern",3),rep ("North Eastern", 6),rep("South Eastern", 3))
a=data.frame(a)
colnames(a)="ZoneDivision"

#comparing the zones
library(plyr)
ddply(n, .(ZoneDivision),summarize,ZoneMatching=Position(isTRUE,ZoneDivision))



Expected Result

   ZoneDivision ZoneMatching
 1      Eastern       NA
 2      Eastern       1
 3       Eastern      1               
 4 North Eastern      0
 5 North Eastern      1
 6 North Eastern      1
 7 North Eastern      1
 8 North Eastern      1
 9 North Eastern      1
 10 South Eastern     0
 11 South Eastern     1
 12 South Eastern     1

Actual Result
    ZoneDivision ZoneMatching
1       Eastern           NA
2 North Eastern           NA
3 South Eastern           NA

How should I proceed? Please help!!

Aucun commentaire:

Enregistrer un commentaire