我有三個橫截面數據集,我試圖將它們合併爲一個縱向數據集。有些措施是不變的(身份證,性別,社區),其他措施隨着時間而變化(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>
我認爲你只是在尋找一個'do.call(rbind,ALLDATA)'? – Arun 2013-04-05 15:36:27
如果您可以發佈樣本輸出即可。頭(數據) – Nishanth 2013-04-05 15:37:56
對不起,我的示例數據有些誤導。我的實際橫截面數據集包含在每個時間段內未測量的變量,因此do.call(rbind,alldata)不起作用。如果所有列都相同,它會很好地工作。上面代碼的輸出已經在上面添加了。 – DBK 2013-04-05 15:48:16