我在数据框中有一个状态列,我想创建两个新列: 一个展望下一阶段变化,一个回顾前一个状态的变化。因此,结果数据框将如下所示:
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”,因为它令人困惑
答案 0 :(得分: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"
(我理解你的第一个请求时遇到了困难,但第二部分遇到了困难。)
答案 1 :(得分: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