在R中将多个宽格式 Dataframe 合并为单个长格式 Dataframe

ig9co6j1  于 2022-12-25  发布在  其他
关注(0)|答案(1)|浏览(113)

我想知道是否有一种方法可以合并宽格式的数据.帧(time1time2time1and2)到一个单一的长格式的数据.帧,以实现我的Desired_output如下?

time1 =read.table(text="

class id   order ac bc
1     1    s-c   1  2

",h=TRUE)

time2 =read.table(text="

class id   order ac bc
1     1    s-c   3  4

",h=TRUE)

time1and2 =read.table(text="

class id   order ex1S ex2S ex1C ex2C
1     1    s-c   8    5    6     1

",h=TRUE)
Desired_output="
class id   order time DV score ave_ex
1     1    s-c   1    ac 1     (8+5)/2 =6.5  # ave_ex = average of `ex`
1     1    s-c   1    bc 2     (8+5)/2 =6.5
1     1    s-c   2    ac 3     (6+1)/2 =3.5
1     1    s-c   2    bc 4     (6+1)/2 =3.5
"
41zrol4v

41zrol4v1#

一个dplyr/tidyr选项可以是绑定前两个表,将它们透视得更长,然后将它们与第三个表连接并进行变异:

library(dplyr)
library(tidyr)

rbind(cbind(time1, time = 1), cbind(time2, time = 2)) %>%
  pivot_longer(ac:bc,names_to = "DV", values_to = "score") %>%
  right_join(time1and2) %>%
  mutate(ave = case_when(
    time == 1 ~ mean(c(ex1S, ex2S)),
    time == 2 ~ mean(c(ex1C, ex2C))
  )) %>%
  select(-c(ex1S:ex2C))

产出

#   class    id order  time DV    score   ave
#   <int> <int> <chr> <dbl> <chr> <int> <dbl>
# 1     1     1 s-c       1 ac        1   6.5
# 2     1     1 s-c       1 bc        2   6.5
# 3     1     1 s-c       2 ac        3   3.5
# 4     1     1 s-c       2 bc        4   3.5

相关问题