2

我有三个横截面数据集,我正在尝试将它们合并为一个纵向数据集。一些度量是恒定的(id、sex、community),而另一些则随时间变化(x1 和 y)。我想要一个长格式的最终​​数据集,上面提到的每个变量都有一列。我认为 merge_recurse() 可以解决问题,但它会为 y 和 x1 分别生成两列(尽管 data12 和 data14 像我希望的那样合并......也许是因为这些变量在第一次合并后被重命名?)。关于如何简单快速地做到这一点的任何想法?下面的示例数据。

#Constant over time
id = seq(1, 100, 1)
sex = sample(c("male","female"), 100, replace=TRUE)
community = sample(c("comA", "comB", "comC", "comD"), 100, replace=TRUE)
#2010
year = rep(2010, 100)
x1 = rnorm(100, mean=5, sd=1)
y = rnorm(100, mean=10, sd=2)
z = rep(5, 100)
data10 = data.frame(cbind(id, year, sex, community, y, x1, z))
#2012
year = rep(2012, 100)
x1 = rnorm(100, mean=6, sd=1)
y = rnorm(100, mean=11, sd=2)
data12 = data.frame(cbind(id, year, sex, community, y, x1))
#2014
year = rep(2014, 100)
x1 = rnorm(100, mean=7, sd=1)
y = rnorm(100, mean=12, sd=2)
data14 = data.frame(cbind(id, year, sex, community, y, x1))
#Merge each year's data
library(reshape)
#Create a list of all datasets
alldata=list(data10, data12, data14)
#Merge data from multiple dataframes
data = merge_recurse(alldata, by=c("id", "year", "sex", "community")

head(data)

id year    sex community              y.x             x1.x z  y.y x1.y
1  1 2010 female      comC 13.1771632561173 4.87556993759158 5 <NA> <NA>
2  2 2010 female      comB 13.7778630888456 6.69677435551805 5 <NA> <NA>
3  3 2010   male      comD 9.42440506678606 3.10067578314296 5 <NA> <NA>
4  4 2010 female      comB 11.0739409098036 4.12318001019941 5 <NA> <NA>
5  5 2010   male      comB 11.6015489242693  4.9565493450503 5 <NA> <NA>
6  6 2010 female      comB 6.52739602897104 3.76896148237067 5 <NA> <NA>
4

1 回答 1

1

我想你正在寻找这个:

all   <- do.call(rbind, alldata)
final <- reshape(all, v.names=c("y", "x1"), idvar=c("id", "sex", "community"),
                 timevar="year", direction="wide")

head(final, 3)
#   id    sex community  y.2010  x1.2010   y.2012  x1.2012   y.2014  x1.2014
# 1  1 female      comA   7.711    5.510   13.952    6.502   11.480    6.629
# 2  2   male      comB   9.130    5.672   11.470    5.500   10.295    7.338
# 3  3   male      comC  15.322    4.889   10.185    5.774   12.257    5.941
于 2013-04-05T17:02:09.353 回答