我有一个dataframe,看起来像这样:
example <- data.frame(
date = as.Date(c('2001-01-01',
'2001-01-02',
'2001-01-01',
'2001-01-02')),
PID_A = c(1091, 1091, 1037, 1037),
PID_B = c(2091, 2091, 2037, 2037),
resp_A = c(3,1,2,4),
resp_B = c(2,4,3,1),
connect_A = c(6,2,5,3),
connect_B = c(5,3,6,2)
)
我想折叠_A
s和_B
s,为每个变量形成一列。但是,每个ID的connect
列应该是其伙伴的值。例如,对于01-01-2001上的PID 1091条目,该行的resp
值应为3(即resp_A),该行的connect
值应为5(即,connect_B,而不是connect_A)。
以下是所需的输出:
example_solution <- data.frame(
date = as.Date(rep(c('2001-01-01',
'2001-01-02'),4)),
PID = c(1091, 1091, 2091, 2091, 1037, 1037, 2037, 2037),
resp = c(3,1,2,4,2,4,3,1),
connect = c(5,3,6,2,6,2,5,3)
)
有人知道一个有效的方法来做到这一点吗?
谢谢你,谢谢!
1条答案
按热度按时间igsr9ssn1#
一个选项是在透视到long之前重命名列: