我有以下融化的样本数据框:
df_melted <- data.frame(ID = c(21, 21, 21, 21, 49, 49, 49, 49), instance = c(1, 1, 1, 1, 1, 1, 2, 2), variable = c("causeofdeath", "deathdate", "dob", "gender", "causeofdeath", "deathdate", "deathdate", "causeofdeath"), value_temp = c("BLANK", "MM/DD/YYYY", "BLANK", "F", "BLANK", "BLANK", "MM/DD/YYYY", "BLANK"))
我最终希望使用以下映射文件来生成新值:
df_map <- data.frame(var_name_1 = c("causeofdeath", "causeofdeath", "dob"), val_1 = c("BLANK", "BLANK", "MM/DD/YYYY"), var_name_2 = c("deathdate", "deathdate", "gender"), val_2 = c("MM/DD/YYYY", "BLANK", "F"), new_var_name = c("ida", "idf", "ids"), new_val = c("T60", "T55", "T67"))
如何重塑 df_melted 使其与 df_map 中所示的特定排列相同?,即:
我尝试使用pivot_wider()但无济于事
您可以在添加一些辅助列后尝试
pivot_wider
,例如p
和grp
df_melted %>%
mutate(p = rep(1:2, length.out = n()), grp = ceiling(row_number() / 2)) %>%
pivot_wider(
names_from = p,
values_from = c(variable, value_temp),
id_cols = c(ID, instance, grp)
)
你将获得
# A tibble: 4 × 7
ID instance grp variable_1 variable_2 value_temp_1 value_temp_2
<dbl> <dbl> <dbl> <chr> <chr> <chr> <chr>
1 21 1 1 causeofdeath deathdate BLANK MM/DD/YYYY
2 21 1 2 dob gender BLANK F
3 49 1 3 causeofdeath deathdate BLANK BLANK
4 49 2 4 deathdate causeofdeath MM/DD/YYYY BLANK