[英]Merging multiple wide-format data.frames into a single long-format data.frame in R
我想知道是否有一种方法可以将宽格式 data.frames( time1
、 time2
、 time1and2
)合并到一个长格式 data.frame 中以实现下面的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
"
一个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.