使宽 Dataframe 变长,但在R中的一对内具有交换值

xytpbqjk  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(72)

我有一个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)
)

有人知道一个有效的方法来做到这一点吗?
谢谢你,谢谢!

igsr9ssn

igsr9ssn1#

一个选项是在透视到long之前重命名列:

library(tidyr)
library(dplyr, warn=FALSE)

example |> 
  rename(connect_A = connect_B, connect_B = connect_A) |> 
  pivot_longer(-date, names_to = c(".value", "who"), names_sep = "_")
#> # A tibble: 8 × 5
#>   date       who     PID  resp connect
#>   <date>     <chr> <dbl> <dbl>   <dbl>
#> 1 2001-01-01 A      1091     3       5
#> 2 2001-01-01 B      2091     2       6
#> 3 2001-01-02 A      1091     1       3
#> 4 2001-01-02 B      2091     4       2
#> 5 2001-01-01 A      1037     2       6
#> 6 2001-01-01 B      2037     3       5
#> 7 2001-01-02 A      1037     4       2
#> 8 2001-01-02 B      2037     1       3

相关问题