我正在努力使用数据集一段时间,以使其从全宽格式转换为全长格式。我设法使它介于两者之间。如下面的玩具示例中所示,数据基于Cond
列采用较长格式。问题在于,测量列名称中的“ _Pre”和“ _Post”必须是另一个因素,例如Cond
,名为PrePost
。这就是为什么我尝试的代码产生错误的结果而导致行过多的原因:
vars_PrePost <- grep("Pre|Post", colnames(df))
df2 <-
df %>%
gather(variable, value, vars_PrePost, -c(ID)) %>%
tidyr::separate(variable, c("variable", "PrePost"), "_(?=[^_]+$)") %>%
spread(variable, value)
这里是玩具数据集:
df <- data.frame(stringsAsFactors=FALSE,
ID = c("10", "10", "11", "11", "12", "12"),
Age = c("23", "23", "31", "31", "24", "24"),
Gender = c("m", "m", "m", "m", "f", "f"),
Cond = c("Cond2", "Cond1", "Cond2", "Cond1", "Cond2", "Cond1"),
Measure1_Post = c(NA, "7", NA, "3", NA, "2"),
Measure1_Pre = c(NA, "3", NA, "2", NA, "2"),
Measure2_Post = c("1.3968694273826", "0.799543118218161",
"1.44098109351048", "0.836960160696351",
"1.99568500539374", "1.75138016371597"),
Measure2_Pre = c("1.19248628113128", "0.726244170934944",
"1.01175268267757", "1.26415857605178",
"2.35250186706497", "1.27070245573958"),
Measure3_Post = c("73", "84", "50", "40", "97", "89"),
Measure3_Pre = c("70", "63", "50", "46", "88", "71")
)
所需的输出应如下所示:
desired_df <- data.frame(stringsAsFactors=FALSE,
Cond = c("Cond2", "Cond2", "Cond1", "Cond1", "Cond2", "Cond2", "Cond1",
"Cond1", "Cond2", "Cond2", "Cond1", "Cond1"),
PrePost = c("Post", "Pre", "Post", "Pre", "Post", "Pre", "Post", "Pre",
"Post", "Pre", "Post", "Pre"),
Measure1 = c(NA, NA, 7, 3, NA, NA, 3, 2, NA, NA, 2, 2),
Measure2 = c(1.3968694273826, 1.19248628113128, 0.799543118218161,
0.726244170934944, 1.44098109351048, 1.01175268267757,
0.836960160696351, 1.26415857605178, 1.99568500539374,
2.35250186706497, 1.75138016371597, 1.27070245573958),
Measure3 = c(73, 70, 84, 63, 50, 50, 40, 46, 97, 88, 89, 71)
)
我希望为此提供一个整洁的/ dplyr解决方案,但是任何解决方案都将不胜感激。谢谢。
pivot_longer(df, matches('_'), names_to = c(".value","PrePost"), names_pattern = "(.*)_(.*)")