【发布时间】:2022-01-26 01:03:42
【问题描述】:
我有一个数据集,我试图用它在 R 中生成不同的数据集。数据集有很多列;但生成新数据集的三个相关列是“Reach”、“Results”和“DV”。范围和结果是数字。 DV 是二进制的 0 和 1。在原始数据集中,所有行的 DV = 0。
对于原始数据集的每一行,我尝试使用一个变量“Reach”并复制该行“reach”次数。 然后对于这组新行,我想将新行的“结果”数(来自原始行)的 DV 从 0 更改为 1。
例如,在原始数据集的第 33 行中:Reach = 1004,Results = 45,DV = 0。新数据集的第 33 行应复制 1004 次,其中 45 行 DV 应从0 到 1。
我为该任务编写的代码可以运行……但由于文件太大,需要 10 多个小时才能运行。关于如何简化此代码以便更快处理的任何想法
empty_new.video <- new.video[FALSE,]
for(i in 1:nrow(new.video)){
n.times <- new.video[i,'Reach'] #determine number of times to repeat rows
if (n.times > 0){
for (j in 1:n.times){
empty_new.video[nrow(empty_new.video) + 1 , ] <- new.video[i,]
}
}
dv.times <- new.video[i,'Results'] #creating dependent variable
if (dv.times>0){
for (k in 1:dv.times){
empty_new.video[nrow(empty_new.video) - n.times + k,'DV'] <- 1
}
}
}
【问题讨论】:
-
@GrzegorzSapijaszko op 在示例中甚至没有使用 rbind,如何加快 rbind 的速度?
-
我的意思是使用 rep 创建所需行的子集,然后将其 rbind 到最终的 df。
标签: r performance for-loop