Transition between variables R

I want to calculate a summary of the transition between variables. I have a dataset that looks like this:

id x.2012 y.2012 x.2013 y.2013
 1      1      0      0      1 
 2      0      1      1      0
 3      0      1      1      0
 4      1      0      1      0

And I want to find the transition table:

        x.2013 y.2013
x.2012       1      1
y.2012       2      0

So, it calculates how many values ​​were changed for x, so zero changes from yto ynext year and 2 for y -> x.

I have no idea how to calculate such a table; I looked through reshape2and tidyr, but without success.


Ideally, I’m looking for a package like reshape(I can’t think of keywords to search Google for this ...) that look like a function cast, while funaccepting a subset my.df:

modern.cast(my.df, .(x.2012, y.2012) ~ .(x.2013, y.2013), fun)
+4
source share
1 answer

Possible solution could be

res <- data.frame(t(apply(df[-1], 1, function(x) names(df[-1])[x != 0])))
library(reshape2)
dcast(res, X1 ~ X2)
#       X1 x.2013 y.2013
# 1 x.2012      1      1
# 2 y.2012      2      0

which ( )

indx <- which(df[-1] != 0, arr.ind = TRUE)
res <- data.frame(matrix(names(df)[-1][indx[order(indx[, 1]), 2]], ncol = 2, byrow = TRUE))
dcast(res, X1 ~ X2)
#       X1 x.2013 y.2013
# 1 x.2012      1      1
# 2 y.2012      2      0
+5

All Articles