【问题标题】:Alternative to speed up the code in R [duplicate]替代加速R中的代码[重复]
【发布时间】:2013-10-12 05:45:15
【问题描述】:

这是我在 R 中运行的代码:

options(stringsAsFactors=FALSE)
x=read.table("sample.txt")
y=read.table("comp.txt")
nrowx=nrow(x)
nrowy=nrow(y)
for(i in 1:nrowx)
{
    flag=0
    for(j in 1:nrowy)
    {
        if(x[i,2]==y[j,2])      
        {
            x[i,2]=y[j,1]
            flag=1
            break
        }
    }
    if(flag==0)
        x[i,]=NA
}

这里 x 有 2,000,000 个条目,而 y 有大约 2,500 个条目。执行 25 个 x 条目大约需要 1 分钟(根据代码)。

在 x 中读取文件的几行:

"X1" "X2"
"1" 53 "all.downtown@enron.com"
"2" 54 "all.enron-worldwide@enron.com"
"3" 55 "all.worldwide@enron.com"
"4" 56 "all_enron_north.america@enron.com"
"5" 56 "ec.communications@enron.com"
"6" 57 "charlotte@wptf.org"
"7" 58 "sap.mailout@enron.com"
"8" 59 "robert.badeer@enron.com"
"9" 60 "tim.belden@enron.com"
"10" 60 "robert.badeer@enron.com"
"11" 60 "jeff.richter@enron.com"
"12" 60 "valarie.sabo@enron.com"
"13" 60 "carla.hoffman@enron.com"
"14" 60 "murray.o neil@enron.com"
"15" 60 "chris.stokley@enron.com"

y 中读取文件的几行:

"X1" "X2"
"1" 1 "jeff.dasovich@enron.com"
"2" 2 "kay.mann@enron.com"
"3" 3 "sara.shackleton@enron.com"
"4" 4 "tana.jones@enron.com"
"5" 5 "vince.kaminski@enron.com"
"6" 6 "pete.davis@enron.com"
"7" 7 "chris.germany@enron.com"
"8" 8 "matthew.lenhart@enron.com"
"9" 9 "debra.perlingiere@enron.com"
"10" 10 "mark.taylor@enron.com"
"11" 11 "gerald.nemec@enron.com"
"12" 12 "richard.sanders@enron.com"
"13" 13 "james.steffes@enron.com"
"14" 14 "steven.kean@enron.com"
"15" 15 "susan.scott@enron.com"

请建议一些替代方法来加快执行速度。 谢谢! :)

【问题讨论】:

  • 你想做什么?匹配数据帧的第二列,如果匹配替换为第一列?你能不能也给我们那 25 行(甚至 10 行)x 和 y?
  • 另外,单位 10 万(100,000)在南亚以外相对不为人知。
  • @Ajanta:我添加了几行我正在执行代码的文件。是的,我正在匹配数据帧的第二列,如果匹配,则将“x”中读取的文件的第二列替换为“y”中读取的文件的第一列。
  • 在函数中而不是全局运行它已经可以加快速度了。
  • 此外,矩阵往往比数据帧快。

标签: r performance


【解决方案1】:

如果我理解正确:

如果y中存在x的email,则取y中属于emailadress的号码,并将x的emailadress替换为y的号码?

x 中行的可能最终结果:

"100" 60 11
"101" NA NA

所以不妨试试这个:

x <- as.matrix(x)
y <- as.matrix(y)

# This matcher is about 2 times faster than the built-in match() function.
matcher <- function(i) {
  w <- which(x[i,2] == y[,2])
  ifelse(length(w) > 0, y[w[1],1], NA)
}

x[,2] <- sapply(1:2000000, function(i) matcher(i))
x[is.na(x[,2]), 1] <- NA

也许首先测试大约 100,000 个案例,看看速度是多少:

sapply(1:100000, function(i) matcher(i))

它会更快的原因是因为您不是在循环中执行循环,而是将问题向量化并使用快速查找匹配方法。

奖金

因为这很容易并行制作,所以考虑一下(如果您的机器有 4 个内核):

myParallel <- function(cores, x, y) {
  require(parallel)
  cl <- makeCluster(cores)
  unlist(parSapply(cl, 1:2000000, function(i) matcher(i))
}
x[,2] <- myParallel(cores=4, x, y)

它可能只允许您在 2 分钟内完成此操作,而不是当前的 5 分 30 秒!

【讨论】:

  • 非常感谢 Dualinity!它工作得真快! :)
  • 你确认它有效吗?花了多长时间?
  • 据我估计还是需要20分钟?
  • 最新版本 13 分钟(这将是大约 6000 倍的速度)
  • 是的!我能够在大约 25 秒内处理 200000 个 x 条目!!
猜你喜欢
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 2016-06-16
  • 2013-03-12
  • 1970-01-01
  • 2014-05-20
  • 2015-08-26
  • 2016-06-13
相关资源
最近更新 更多