[英]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.