在几列中折叠具有不同值的复制行在我的数据框中,测试年份和年龄有相同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