【发布时间】:2013-12-05 16:15:59
【问题描述】:
我有一个 100 行和 65 列的数据框(称为 crossID)。此数据框可以包含重复项,但这些重复项是连续的(我的意思是,如果第 31 行有重复项,则重复项将在第 32 行,并且仅在其中)。
我只是想提取不重复的行并将它们复制到一个新的数据帧中(我称为 crossID_clean)。我想提取重复的行并将它们放在另一个数据框中(我称为 crossDup)
我写了这段代码:
crossID_clean = data.frame()
crossDup = data.frame()
for (i in 1:nrow(crossID)){
if(crossID[i,1] != crossID[i+1,1]){
crossID_clean = rbind(crossID_clean, crossID[i,])
ncross=ncross+1 #good crossmatches
}else{
crossDup = rbind(crossDup, crossID[i,]) #List of duplicated crossmatches
ndel = ndel+1 #objects deleted because having more than one crossmatch
}
}
最终出现错误:
Error in rbind(deparse.level, ...) :
numbers of columns of arguments do not match
我不明白问题出在哪里,因为两个新数据框没有指定列,所以我认为“列数”不可能有问题......
我在其他帖子中阅读了如何在循环中创建数据帧以及如何将行附加到新数据帧,但我发现的只是使用 1 个数据帧时(如在writing to a dataframe from a for-loop in R),而不是通过玩两个或更多数据框。对不起,如果已经有这个帖子。非常感谢您的帮助。
谢谢。
【问题讨论】:
-
就像在 R 中经常出现的情况一样,
for循环不是解决这个问题的好方法,您可以使用一个专门的函数。阅读help("duplicated")。
标签: r