I have a table like this:
df <- data.frame(P1 = c(1,0,0,0,0,0,"A"),
P2 = c(0,-2,1,2,1,0,"A"),
P3 = c(-1,2,0,2,1,0,"B"),
P4 = c(2,0,-1,0,-1,0,"B"),
Names = c("G1","G2","G3","G1","G2","G3","Group"),
stringsAsFactors = FALSE)
Which becomes
Names P1 P2 P3 P4
G1 1 0 -1 2
G2 0 -2 2 0
G3 0 1 0 -1
G1 0 2 2 0
G2 0 1 1 -1
G3 0 0 0 0
Group A A B B
Here, A and B are grouping variables for P1, P2, P3, P4.
I want to build a contingency for Ids (G1, G2...), Group (A,B), and Var (-2,-1,0,1,2) table such as:
Id Group Var Count
G1 A -2 0
G1 A -1 0
G1 A 0 1
G1 A 1 1
G1 A 2 0
G1 B -2 0
G1 B -1 1
G1 B 0 0
G1 B 1 0
G1 B 2 1
G2 A -2 1
G2 A -1 0
G2 A 0 1
...
Is there a way to do it in R without using lots of loops?
Assuming you want to group the
P1&P2columns asAand theP3&P4columns asB, you could approach it as follows with thedata.table-package:which results in:
Used data:
Note that I omitted the 'Group'-row because you stated in the comments that these were just to indicated to which groups the
P1-P4columns should belong.