我有一张这样的桌子:
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)
变成
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
在这里,A
和B
是对 的变量进行分组P1, P2, P3, P4
。
我想为Ids
( G1
, G2
...), Group
( A
, B
) 和Var
( -2,-1,0,1,2
) 表建立一个应急方案,例如:
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
...
有没有办法在不使用大量循环的情况下在 R 中做到这一点?