【发布时间】:2020-12-25 17:11:17
【问题描述】:
我有一个关于人们住宅流动性的数据集,我想研究某些疾病方面。我收到了 excel 格式的数据,问题是每个独特的人都有多行,类似于一个人居住的不同位置。一个虚拟示例与此类似:
dput(df)
df <- structure(list(caseid = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L), startdate = c(2001L, 2008L,
2012L, 1990L, 2009L, 1998L, 1999L, 2002L, 2003L, 2007L, 2011L,
2015L, 2003L, 2013L, 2013L, 2019L, 2004L), enddate = c(2008L,
2012L, NA, 2009L, NA, 1999L, 2002L, 2003L, 2007L, 2011L, 2015L,
NA, 2013L, 2013L, 2019L, NA, NA), cityno = c(418L, 20L, 420L,
544L, 132L, 312L, 350L, 312L, 350L, 99L, 99L, 351L, 862L, 863L,
861L, 43L, 449L), location = c("north", "south", "north", "mid",
"south", "mid", "mid", "mid", "mid", "south", "south", "mid",
"north", "north", "north", "south", "north")), class = "data.frame", row.names = c(NA,
-17L))
> df
caseid startdate enddate cityno location
1 1 2001 2008 418 north
2 1 2008 2012 20 south
3 1 2012 NA 420 north
4 2 1990 2009 544 mid
5 2 2009 NA 132 south
6 3 1998 1999 312 mid
7 3 1999 2002 350 mid
8 3 2002 2003 312 mid
9 3 2003 2007 350 mid
10 3 2007 2011 99 south
11 3 2011 2015 99 south
12 3 2015 NA 351 mid
13 4 2003 2013 862 north
14 4 2013 2013 863 north
15 4 2013 2019 861 north
16 4 2019 NA 43 south
17 5 2004 NA 449 north
每个ID都有不同数量的位置,没有变量包含居住标签(residence1、residence2等...)
例如,我想研究在某个地点是否会增加患上这种疾病的几率。我认为第一步是将数据更改为广泛的格式,以便根据 ID 的居住位置对其进行分类。我尝试了spread 和dcast,但他们需要有一个额外的变量来描述住所(在dcast 中创建一个公式)。我找不到如何创建这样一个变量,我不确定我是否做对了,有什么想法吗?
Ps:这是我第一次在这里发布问题,如果我没有以正确的方式提供信息,请注意。
【问题讨论】:
-
请使用
dput分享一个具有预期输出的可重现的小示例。很难从图像中复制以进行测试。谢谢 -
您可能需要的函数是
tidyr::pivot_wider()。如果您提供示例输出 - 几行就可以了 - 您希望数据框在宽格式中看起来像什么,我可以更具体。