r - 改善循环的运行时间

标签 r loops sqldf

我正在尝试提高以下过程的计算效率。我已经使用数据创建了玩具示例以供审查。第一种方法的运行时间是第二种方法的一半。

我如何改进第一种方法的运行时间?

library(sqldf)
id = c(1,1,1,1,2,2,2,5,5,5,5,5,5)
qn = c(0,0,1,1,0,1,0,0,0,1,0,1,0)
d = data.frame(cbind(id,qn))
names(d) = c("id", "qn")

un = unique(d$id)
holder = matrix(0,length(un), 1)
counter = 0

x = proc.time()

for (i in un)
{
  z = head(which(d[d$id == i,]$qn==1),1)
  counter = counter + 1
  holder[counter,] = z
}

proc.time() - x
f = sqldf("select id, count(qn) from d group by id", drv = 'SQLite')
f = cbind(f,holder)
#################################
un = unique(d$id)
holder = matrix(0,length(un), 1)
counter = 0

x = proc.time()

for (i in 1:length(un))
{
  y = paste("select * from d where id = ", un[i])
  y = sqldf(y, drv = 'SQLite')
  y = min(which(y$qn==1))
  counter = counter + 1
  holder[counter,] = y
}

proc.time() - x
f = sqldf("select id, count(qn) from d group by id", drv = 'SQLite')
f = cbind(f,holder)

我正在尝试为每个 id 计算 1 的第一个实例。

预期输出:

# id first
# 1:  1     3
# 2:  2     2
# 3:  5     3

最佳答案

我们也可以使用data.table

library(data.table)
setDT(d)[, list(first= which.max(qn)) , id]

关于r - 改善循环的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33228671/

相关文章:

R矩阵包: Demean sparse matrix

r - 如何根据来自多个列的多个条件创建一个新列?

python - 加快Python中的集成功能

javascript - 使用 HTTP 请求关闭 for 循环

mysql - SQL - 在包含数字和字母的列中搜索特定范围的最佳方法是什么?

RSQLite loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) 中出现错误 : namespace ‘DBI’ 0. 4-1 正在加载,但需要 >= 0.8

r - 动物园里的动物 : can we aggregate a daily time series of factors and flag activity by ID?

r - 将垂直线添加到ggplot条形图

r - 可移植 R 中的 tcltk

c - `while(1)`如何优化不占用所有资源?