在R中,我有一个大型数据框,其中前两列是主ID(对象)和辅助ID(对象的元素)。我想创建此数据帧的子集,条件是主ID和辅助ID必须在以前的数据帧中重复20次。我还要为具有相同结构的其他数据帧重复此过程。
现在,我首先计算每个值(主要和次要ID)在新数据帧中重复多少次,然后使用for
循环创建新数据帧,但过程非常缓慢且效率低下:循环从具有500.000到100万行的数据帧开始写入20行/秒。
for (i in 1:13){
x <- fread(dataframe_list[i]) #list which contains the dataframes that have to be analyzed
x1 <- ddply(x,.(Primary_ID,Secondary_ID), nrow) #creating a dataframe which shows how many times a couple of values repeats itself
x2 <- subset(x1, x1$V1 == 20) #selecting all couples that are repeated for 20 times
for (n in 1:length(x2$Primary_ID)){
x3 <- subset(x, (x$Primary_ID == x2$Primary_ID[n]) & (x$Secondary_ID == x2$Secondary_ID[n]))
outfiles <- paste0("B:/Results/Code_3_", Band[i], ".csv")
fwrite(x3, file=outfiles, append = TRUE, sep = ",")
}
}
例如,如何从前一个数据帧中获取主数据库和辅助ID的值,一次获取x2数据帧中的值,而不是一次写入一组20行?也许在SQL中更容易,但我现在必须处理R.
编辑:
当然。假设我是从这样的数据帧开始的(其他行有重复的ID,我只需要停止5行就可以了):
Primary ID Secondary ID Variable
1 1 1 0.5729
2 1 2 0.6289
3 1 3 0.3123
4 2 1 0.4569
5 2 2 0.7319
然后用我的代码我在一个新的数据帧中计算重复的行(阈值为4而不是20,所以我可以给你一个简短的例子):
Primary ID Secondary ID Count
1 1 1 1
2 1 2 3
3 1 3 4
4 2 1 2
5 2 2 4
想要的输出应该是这样的数据帧:
Primary ID Secondary ID Variable
1 1 3 0.5920
2 1 3 0.6289
3 1 3 0.3123
4 1 3 0.4569
5 2 2 0.7319
6 2 2 0.5729
7 2 2 0.6289
8 2 2 0.3123
如果有人有兴趣,我设法找到了办法。在使用上面的代码计算重复几次值的次数之后,可以通过这种简单的方式获得我想要的输出:
#Select all the couples that are repeated 20 times
x2 <- subset(x1, x1$V1 == 20)
#Create a dataframe which contains the repeated primary and secondary IDs from x2
x3 <- as.data.frame(cbind(x2$Primary_ID, x2$Secondary_ID)
#Wanted output
dataframe <- inner_join(x, x3)
#Joining, by c("Primary_ID", "Secondary_ID")