我希望在通过生成单个变量的编号版本将长数据帧转换为宽格式后撤消reshape
。当有多个关键变量和需要重新组合的多个变量时,我面临的挑战就是这样做。我尝试使用gather
中的tidyr
无效。以长数据为例:
toy = data.frame(
first_key = rep(c("A", "B", "C"), each = 6),
second_key = rep(rep(c(1:2), each = 3), 3),
colors = c("red", "yellow", "green", "blue", "purple", "beige"),
days = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"),
index = c(1:3)
)
其中提供了以下data.frame:
first_key second_key colors days index
A 1 red Monday 1
A 1 yellow Tuesday 2
A 1 green Wednesday 3
A 2 blue Thursday 1
A 2 purple Friday 2
A 2 beige Saturday 3
B 1 red Monday 1
B 1 yellow Tuesday 2
B 1 green Wednesday 3
B 2 blue Thursday 1
B 2 purple Friday 2
B 2 beige Saturday 3
C 1 red Monday 1
C 1 yellow Tuesday 2
C 1 green Wednesday 3
C 2 blue Thursday 1
C 2 purple Friday 2
C 2 beige Saturday 3
使用编号版本的变量将其重新整理为宽格式,如下所示:
toy_wide = reshape(toy, idvar = c("first_key", "second_key"),
timevar = "index", direction = "wide", sep = "_")
并给出了这种宽格式:
first_key second_key colors_1 days_1 colors_2 days_2 colors_3 days_3
A 1 red Monday yellow Tuesday green Wednesday
A 2 blue Thursday purple Friday beige Saturday
B 1 red Monday yellow Tuesday green Wednesday
B 2 blue Thursday purple Friday beige Saturday
C 1 red Monday yellow Tuesday green Wednesday
C 2 blue Thursday purple Friday beige Saturday
但是如何让它恢复原始格式?我试过以下但是我收到了一个错误。
tidyr::gather(toy_wide, key = c("first_key", "second_key"), value = c("days", "colors"),
colors_1:days_3, factor_key = TRUE)
错误:列规范无效
答案 0 :(得分:4)
如果您使用reshape
扩展,请再次使用reshape
:
reshape(toy_wide, idvar = c("first_key", "second_key"), timevar="index",
varying=3:8, direction="long", sep="_")
# first_key second_key index colors days
#A.1.1 A 1 1 red Monday
#A.2.1 A 2 1 blue Thursday
# ...
如果指定varying=
个变量集(可以是列值3:8
的列表),则列值将删除-(1:2)
,或列名称作为字符向量{{1 }}和c("a","b")
然后sep=
将能够适当地猜测输出变量名称。
通过多个步骤进行这些类型的重构以保持清晰并自动更好地自动化通常很有帮助:
reshape
答案 1 :(得分:1)
以下是来自melt
的{{1}}的另一个选项,可能需要多个data.table
measure
。
patterns