问题
I have some data which has a number of different id's in it and a list of their states at different times (t1, t2, t3 etc) and I'd like to generate a table that gives information about the different types of state change that happen, so something that would look like this for the sample data (copied below).
x y z
x 0 2 0
y 1 2 1
z 1 0 2
Which would show, for example, that x
changed to y
twice and y
changed to x
once. Does anyone know how I might be able to do this in R?
SAMPLE DATA:
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)
回答1:
One way you can do this is by using igraph
. The slightly tricky bit is getting it in a graph format, but after that is done the adjacency matrix can be extracted.
# 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
来源:https://stackoverflow.com/questions/46300747/how-can-i-produce-a-table-of-transition-types-in-r