【问题标题】:Optimize the performance of a function优化函数的性能
【发布时间】:2014-11-18 14:38:14
【问题描述】:

我在下面创建了以下函数,用于在 data.frame 的新列中将真实值与预测值(当真实值不存在时)合并,该函数确实有效,但我想对其进行优化,因为使用数据集我工作,该功能大约需要两个小时才能运行..如果有人可以帮助我,我将不胜感激。

p <-            
  function(object, newdata = NULL, type = c("link", "response", "terms"), 
           rse.fit = FALSE, dispersion = NULL, terms = NULL,
           na.action = na.pass, ...)
  { 
{
    pred <- predict (object,newdata)    

      }

    vetor1 <- (newdata$ALT)         # Creates a column vector from the actual heights of the data.frame
    vetor1[is.na(vetor1)] <- 0      # Replaces the NA's present in the vector created above the numeric value 0
    vetor2 <- c(pred)           # Creates a vector from the predicted data
    for(i in 1:length(vetor1)){     # The loop is executed until all values vector1 pass the following condition
      if(vetor1[i]==0.00){      # If a value of the first vector has the value 0, ie, if it is absent
        vetor1[i]=vetor2[i]     # Then the predicted value will replace the missing value
        newdata$ALTMISTA <- vetor1  # The vector1, already possessing the actual values and the predicted values merged into the same vector goes                   on to become a new column in data.frame, this column is called a ALTMISTA
      }
    }
    return (newdata)            
  }

【问题讨论】:

  • 您好,欢迎来到 StackOverflow!有关优化代码的问题应在CodeReview StackExchange 提出
  • @JohnOdom 不一定。我们经常在这里考虑(写得很好:-))对代码模块的请求,因为经常有一些现有的库或 R 包可以大大加快各种数据处理步骤。
  • @CarlWitthoft 哦,好吧,我想我误解了两页之间的区别,谢谢!

标签: r function loops for-loop optimization


【解决方案1】:

几个想法:如果你有一个 gigundo 数据集,那么这需要时间;或者你需要学习使用parallel 包。

我认为您不想每次通过循环都重新定义newdata$ALTMISTA,因为您只是在覆盖这些值。

您可以通过对ifelse 使用矢量化操作来删除i 循环:

 set.seed(1)
 foo<-sample(c(-1,1),10,rep=T)
 foo
 [1] -1 -1  1  1 -1  1  1  1  1 -1
 bar<-11:20
 foo<- ifelse(foo<0, foo,bar)
 foo
 [1] -1 -1 13 14 -1 16 17 18 19 -1

但正如我所说,我怀疑你有一个大型数据集,predict 很可能是时间猪。尝试使用Rprof 找出时间都花在了哪里。

【讨论】:

  • 您好,我曾尝试过类似的方法,但是当我使用 ifelse 或 while 时,例如,他可以用预测但“无序”替换缺失值。例如,正确的应该如下: 实际值 = c (1,5,6,0,0,4) 预测值 = c (2,4,6,3,5,4) 最终向量 c = (1 ,5,6,3,5,4) 但是,最终向量如下: 最终向量 c = (1,5,6,2,4,4) 并且离开循环函数很慢并且没有预测值.. 无论如何,感谢您的帮助!
  • 我无法理解您评论中的操作。如果您可以发布一个小样本数据集,即 prednewdata$ALT ,我可以向您展示如何使用 ifelse 来获得您想要的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
相关资源
最近更新 更多