在幾列中摺疊具有不同值的複製行在我的數據框中,測試年份和年齡有相同ID但行數不同的行。我想摺疊重複的行併爲不同的值創建新的列。使用R
我是新來的R,一直在努力。
這是該數據幀:
>df id project testyr1 testyr2 age1 age2 1 16S AS 2008 NA 29 NA 2 32S AS 2004 NA 30 NA 3 37S AS NA 2011 NA 36 4 50S AS 2004 NA 23 NA 5 50S AS 1998 NA 16 NA 6 55S AS 2007 NA 28 NA
testyr1
應該有最早的一年testyr2
最近一年。 age1
應該是較年輕的年齡段和age2
年齡較大的年齡段。
輸出應該是:
id project testyr1 testyr2 age1 age2 1 16S AS 2008 NA 29 NA 2 32S AS 2004 NA 30 NA 3 37S AS NA 2011 NA 36 4 50S AS 1998 2004 16 23 6 55S AS 2007 NA 28 NA
我試着寫一個循環,但不知道如何收場吧:
df.undup <- c()
df.undup <- c()
for (i in 1:nrow(df)){
if i == i+1
df$testyr1 != NA {
testyr2 = max(testyr1)
testyr1 = min(testyr1)
nage2 = max(nage1)
nage1 = min(nage1)
}
else{
testyr2 = max(testyr2)
testyr1 = min(testyr2)
nage2 = max(nage2)
nage1 = min(nage2)
}
}
任何幫助將不勝感激。
你可以只有兩個重複? – nico 2012-07-31 20:30:09