0

我在数据框中有一个状态列,我想创建两个新列:一个展望下一个阶段的变化,一个回顾上一个状态变化。因此生成的数据框将如下所示:

state coming  previous
  a     a-b     NA
  a     a-b     NA
  a     a-b     NA
  a     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
  a     NA      c-a
  a     NA      c-a

或者甚至更好,但现在您只需创建两个转换列:

state trans1   trans2
  a     a-b     NA
  a     a-b     NA
  a     a-b     NA
  a     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
  a     c-a     NA 
  a     c-a     NA

[编辑] 将名为“1”的状态更改为“c”,因为它令人困惑

4

2 回答 2

1

让我们给那个数据框起一个名字,比如'inp'。使用rle函数构造“状态”序列:

> 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"

(我能够克服理解您的第一个请求的困难,但在第二部分中一直存在困难。)

于 2012-06-12T13:13:59.860 回答
0

感谢 DWin 的回答,我自己找到了第二部分的答案。这是创建带有转换列的数据框的完整代码:

state = rep(c('a','b','c','a'), c(4,3,3,2))
inp=data.frame(state, vals=rnorm(12))
runinps=rle(as.character(inp$state)) # doesn't work without as.character

(rs <- runinps$values)
(ls=runinps$lengths)

(inp$coming <- rep( c( paste( rs[-length(rs)], rs[-1], sep="-"), NA), ls ))
(inp$previous <-rep( c( NA, paste(rs[-length(rs)], rs[-1], sep="-")), ls ))

# Create the first transitions column
(reps=rep(1:(length(ls)/2),each=2))
(ls2=as.vector(tapply(ls , reps, sum)))
seqRs=seq(from=1,to=length(rs),by=2)
(inp$trans <- rep(paste( rs[seqRs], rs[seqRs+1], sep="-"), ls2 ))

# Create the second transitions column
reps=c(reps[-1], max(reps)+1)
(ls2=as.vector(tapply(ls , reps, sum)))
seqRs=seq(from=2,to=length(rs)-1,by=2)
(inp$trans2 <- rep(c(NA, paste( rs[seqRs], rs[seqRs+1], sep="-"), NA), ls2 ))

# some last commands to create one transition column
inp2=subset(inp,!is.na(inp$trans2))
inp2$trans=inp2$trans2
inp=rbind(inp,inp2)
inp$trans2<-NULL
于 2012-06-12T19:59:03.233 回答