dataframe - How can I create a transitions column in R -


i have state column in dataframe , want create 2 new columns: 1 looks ahead next stage change , 1 looks previous state change. resulting dataframe below:

state coming  previous       a-b     na       a-b     na       a-b     na       a-b     na   b     b-c     a-b   b     b-c     a-b   b     b-c     a-b   c     c-a     b-c   c     c-a     b-c   c     c-a     b-c       na      c-a       na      c-a 

or maybe better, create 2 transition columns:

state trans1   trans2       a-b     na       a-b     na       a-b     na       a-b     na   b     a-b     b-c    b     a-b     b-c   b     a-b     b-c   c     c-a     b-c   c     c-a     b-c   c     c-a     b-c       c-a     na        c-a     na 

[edit] changed states named "1" "c" because confusing

let's give dataframe name, 'inp'. use rle function construct sequence of "states":

> rle(inp$state) run length encoding   lengths: int [1:4] 4 3 3 2   values : chr [1:4] "a" "b" "1" "a"  runinp <- rle(inp$state)$values paste( runinp[-length(runinp)], runinp[-1], sep="-") # [1] "a-b" "b-1" "1-a" inp$coming <- rep( c( paste( runinp[-length(runinp)], runinp[-1], sep="-"), na),                      rle(inp$state)$lengths ) inp$coming # [1] "a-b" "a-b" "a-b" "a-b" "b-1" "b-1" "b-1" "1-a" "1-a" "1-a" na    na     inp$previous <-   rep( c( na_character_, paste(runinp[-1], runinp[-length(runinp)], sep="-")),        rle(inp$state)$lengths ) inp$previous  [1] na    na    na    na    "b-a" "b-a" "b-a" "1-b" "1-b" "1-b" "a-1" "a-1" 

(i able overcome difficulty understanding first request, had persistent difficulty second part.)


Comments

Popular posts from this blog

How do you change vbulletin's home page to the forums instead of the default (CMS or Activity Stream)? -

c++ - Troubles when compiling phash program -