data <- data.frame(
T2_husband = rnorm(5),
T2_wife = rnorm(5),
T1_husband = rnorm(5),
T1_wife = rnorm(5),
Dyad_ID = 1:5
)
所以我的数据集中有 5 列。 但是,我想让数据集具有以下列
二元ID 角色(表明这是丈夫还是妻子) My_T1(自身的T1分数) My_T2(自身的T2分数) Partner_T1(伴侣的T2分数,如果该行是丈夫,则为妻子分数。如果该行是妻子,则为丈夫分数) 伙伴_T2.
# Reshape the dataset
reshaped_data <- data %>%
pivot_longer(
cols = c(T1_husband, T1_wife, T2_husband, T2_wife), # Columns to reshape
names_to = c("Time", "Role"), # Split column names into "Time" and "Role"
names_sep = "_" # Separator is "_"
) %>%
pivot_wider(
id_cols = c(Dyad_ID, Role), # Keep Dyad_ID and Role as unique identifiers
names_from = Time, # Reshape Time into separate columns
values_from = value # Values go into "T1" and "T2" columns
)
# Add My_* and Partner_* columns
reshaped_data <- reshaped_data %>%
group_by(Dyad_ID) %>% # Group by Dyad_ID to match partner roles
mutate(
My_T1 = T1,
My_T2 = T2,
Partner_T1 = T1[Role != first(Role)], # Select T1 where Role is not the current Role
Partner_T2 = T2[Role != first(Role)] # Select T2 where Role is not the current Role
) %>%
ungroup() %>% # Remove grouping
select(Dyad_ID, Role, My_T1, My_T2, Partner_T1, Partner_T2)
这是我尝试过的,但我认为它没有达到我的预期。
我认为你只需要稍微修改一下创建Partner_T1和Partner_T2的方式,其余代码与你的相同
# Reshape the dataset
reshaped_data <- data %>%
pivot_longer(
cols = c(T1_husband, T1_wife, T2_husband, T2_wife), # Columns to reshape
names_to = c("Time", "Role"), # Split column names into "Time" and "Role"
names_sep = "_" # Separator is "_"
) %>%
pivot_wider(
id_cols = c(Dyad_ID, Role), # Keep Dyad_ID and Role as unique identifiers
names_from = Time, # Reshape Time into separate columns
values_from = value # Values go into "T1" and "T2" columns
)
reshaped_data <- reshaped_data %>%
group_by(Dyad_ID) %>% # Group by Dyad_ID to match partner roles
mutate(
My_T1 = T1,
My_T2 = T2,
Partner_T1 = ifelse( Role == "husband", T1[Role != first(Role)], T1[Role == first(Role)]), # Select T1 where Role is not the current Role
Partner_T2 = ifelse( Role == "husband", T2[Role != first(Role)], T2[Role == first(Role)]) # Select T2 where Role is not the current Role
) %>%
ungroup() %>% # Remove grouping
select(Dyad_ID, Role, My_T1, My_T2, Partner_T1, Partner_T2)