坚持使用基础 R reshape()
,请尝试以下操作。
我认为我已经使用以下内容重新创建了您的示例数据:
Copy.of.BP_2 <-
structure(list(CODEA = c(1, 3, 4), C45 = c(NA, 2, 2), ragek = c(3,
3, 3), ra80 = c(4, 3, 6), ra98 = c(1, 1, 1), CBCLAggressionAt1410 = c(NA,
0, NA), CBCLInternalisingAt1410 = c(NA, 0, NA), Obese14 = c(NA,
0, NA), Overweight14 = c(NA, 0, NA), Overweight21 = c(NA, 1,
NA), Obese21 = c(NA, 0, NA), hibp14 = c(NA, 0, NA), hibp21 = c(NA,
0, NA)), .Names = c("CODEA", "C45", "ragek", "ra80", "ra98",
"CBCLAggressionAt1410", "CBCLInternalisingAt1410", "Obese14",
"Overweight14", "Overweight21", "Obese21", "hibp14", "hibp21"
), row.names = c(NA, -3L), class = "data.frame")
Copy.of.BP_2
# CODEA C45 ragek ra80 ra98 CBCLAggressionAt1410 CBCLInternalisingAt1410
# 1 1 NA 3 4 1 NA NA
# 2 3 2 3 3 1 0 0
# 3 4 2 3 6 1 NA NA
# Obese14 Overweight14 Overweight21 Obese21 hibp14 hibp21
# 1 NA NA NA NA NA NA
# 2 0 0 1 0 0 0
# 3 NA NA NA NA NA NA
首先,为方便起见,让我们创建一个度量变量的向量——我们想要从宽格式到长格式“堆叠”的变量。
measurevars <- names(Copy.of.BP_2)[grepl("Obese|Overweight|hibp",
names(Copy.of.BP_2))]
接下来,使用reshape()
,指定方向、标识变量以及哪些变量随时间“变化”(measurevars
,从上面)。
BP_2_long <- reshape(Copy.of.BP_2, direction = "long", idvar="CODEA",
varying = measurevars, sep = "")
BP_2_long
# CODEA C45 ragek ra80 ra98 CBCLAggressionAt1410 CBCLInternalisingAt1410
# 1.14 1 NA 3 4 1 NA NA
# 3.14 3 2 3 3 1 0 0
# 4.14 4 2 3 6 1 NA NA
# 1.21 1 NA 3 4 1 NA NA
# 3.21 3 2 3 3 1 0 0
# 4.21 4 2 3 6 1 NA NA
# time Obese Overweight hibp
# 1.14 14 NA NA NA
# 3.14 14 0 0 0
# 4.14 14 NA NA NA
# 1.21 21 NA NA NA
# 3.21 21 0 1 0
# 4.21 21 NA NA NA
如果您只对 id 列和 measure 列感兴趣,您还可以在命令中添加一个drop
参数:reshape()
BP_2_long_2 <- reshape(
Copy.of.BP_2, direction = "long", idvar="CODEA",
varying = measurevars, sep = "",
drop = !names(Copy.of.BP_2) %in% c(measurevars, "CODEA"))
BP_2_long_2
# CODEA time Obese Overweight hibp
# 1.14 1 14 NA NA NA
# 3.14 3 14 0 0 0
# 4.14 4 14 NA NA NA
# 1.21 1 21 NA NA NA
# 3.21 3 21 0 1 0
# 4.21 4 21 NA NA NA
更新:为什么您的代码不起作用
这是您尝试过的内容的逐个参数细分,并附有有关如何尝试修复它的评论。
BP.stack1 =
reshape(Copy.of.BP_2, # Fine
timevar="time", # Fine
direction="long", # Fine
varying=list(names(Copy.of.BP_2)[8:13]), # Wrong. Use "varying = 8:13" instead
v.names="Obese","Overweight","HiBP", # Wrong. This needs to be in c()
idvar=c("CODEA") # Almost... missing your closing ")"
因此,要获得完整的工作命令:
BP.stack1 = reshape(
Copy.of.BP_2,
timevar="time",
direction="long",
varying=8:13,
v.names=c("Obese", "Overweight", "HiBP"),
idvar=c("CODEA"))
我通常尽量不要过多地依赖列号,因为与要重命名的列相比,这些列更有可能被重新排列。因此,我使用grepl()
根据某种模式匹配名称。