unk*_*own 2 r time-series dynamic data-analysis
我有一些数据,其中有许多不同的id和不同时间(t1,t2,t3等)的状态列表,我想生成一个表,提供有关不同类型的状态变化的信息,发生了,所以对于样本数据看起来像这样(下面复制).
x y z
x 0 2 0
y 1 2 1
z 1 0 2
Run Code Online (Sandbox Code Playgroud)
例如,哪个会显示x更改为y两次并y更改为x一次.有谁知道我怎么能在R中做到这一点?
样本数据:
id <- c('a','b','c')
t1 <- c('x','y','z')
t2 <- c('y','y','z')
t3 <- c('z','y','x')
t4 <- c('z','x','y')
df <- cbind(id, t1, t2, t3, t4)
Run Code Online (Sandbox Code Playgroud)
你可以这样做的一种方法是使用igraph.稍微棘手的一点是以图形格式获取它,但在此之后,可以提取邻接矩阵.
# Split matrix so that each row is a `path`
lst <- split(df[,-1], 1:nrow(df))
unique_nodes <- unique(c(df[,-1]))
library(igraph)
# Create empty graph and name nodes
g <- make_empty_graph(n=length(unique_nodes))
V(g)$name <- unique_nodes
# Read in each path
for (i in lst) {
g <- g + path(i)
}
# Output adjacency matrix
as_adj(g, sparse=FALSE)
# x y z
#x 0 2 0
#y 1 2 1
#z 1 0 2
Run Code Online (Sandbox Code Playgroud)