以下代码将向量与数据帧组合:
newrow = c(1:4)
existingDF = rbind(existingDF,newrow)
但是,此代码始终在数据帧的末尾插入新行。
如何在数据框架中的指定点插入行?例如,假设数据帧有20行,我如何在行10和11之间插入新行?
这里有一个解决方案,避免了(通常很慢)rbind调用:
existingDF
r
newrow
insertRow
existingDF[seq(r+1,nrow(existingDF)+1),]
existingDF[r,]
existingDF
}
> insertRow(existingDF, newrow, r)
V1 V2 V3 V4
1 1 6 11 16
2 2 7 12 17
3 1 2 3 4
4 3 8 13 18
5 4 9 14 19
6 5 10 15 20
如果速度不如清晰度重要,那么@ Simon的解决方案很好:
existingDF
> existingDF
V1 V2 V3 V4
1 1 6 11 16
2 2 7 12 17
3 3 8 13 18
4 1 2 3 4
41 4 9 14 19
5 5 10 15 20
(注意我们用不同的方式索引r)。
最后,基准:
library(microbenchmark)
microbenchmark(
rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
insertRow(existingDF,newrow,r)
)
Unit: microseconds
expr min lq median uq max
1 insertRow(existingDF, newrow, r) 660.131 678.3675 695.5515 725.2775 928.299
2 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 801.161 831.7730 854.6320 881.6560 10641.417
基准
[email protected],基准需要检查缩放,因为问题的大小增加。这里我们去:
benchmarkInsertionSolutions
existingDF
r
newrow
m
rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
insertRow(existingDF,newrow,r),
insertRow2(existingDF,newrow,r)
)
# Now return the median times
mediansBy
res
names(res)
res
}
nrows
benchmarks
colnames(benchmarks)
ggplot( melt(benchmarks), aes(x=Var2,y=value,colour=Var1) ) + geom_line() + scale_x_log10() + scale_y_log10()
@ Roland的解决方案相当不错,即使调用rbind:
5 50 500 5000 50000 5e+05
insertRow2(existingDF, newrow, r) 549861.5 579579.0 789452 2512926 46994560 414790214
insertRow(existingDF, newrow, r) 895401.0 905318.5 1168201 2603926 39765358 392904851
rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 787218.0 814979.0 1263886 5591880 63351247 829650894
按线性标度绘制:
和对数对数标度: