r - 优化 R 中的 Apply() While()

标签 r algorithm optimization package

以下数据用于进行比较分析。我使用 apply() 编写了代码和 while() ,即使它按预期工作,我也没有成功地进一步优化它。在更大的数据集中,当前运行时间超过几个小时。

以下是小型示例数据集:

data_1

A B C D
2 1 3 2.5

data_2

P Q R S
3 2 4 5.5

数据

 A   B   C   D
1.0 0.5 1.3 1.5
1.5 1.2 5.5 3.5
1.1 0.5 1.3 1.5
1.5 1.2 5.5 3.5
1.5 1.2 5.5 3.5
1.1 0.5 1.3 1.5
1.5 1.2 5.5 3.5
1.0 0.5 1.3 1.5

代码

# Row counter 
rowLine <<- 0

# Set current column to first one
columnLine <<- 1

# Preserve column header and dimensions for final data
finalData <- Data

# Find recursively
findThreshold <- function () {

  if ( columnLine <= ncol(Data) ){

    # Initialize row navigation to zero
    rowLine  <<- 1

    # Navigate through rows
    while (rowLine <= nrow(Data)){

      # If outside threshold
      if ( (Data[rowLine, columnLine] < data_1[columnLine]) |
           (Data[rowLine, columnLine] > data_2[columnLine])){

        finalData[rowLine, columnLine] <<- 1

      } else {

        finalData[rowLine, columnLine] <<- 0

      }

      # Increment row counter
      rowLine <<- rowLine + 1

    }
  }

  # Increment column counter
  columnLine <<- columnLine + 1

}

# Apply
apply(Data, 2, function(x) findThreshold())

我也明白使用 <<-loops 一起使用时是一个很大的否定递归分析如 apply() .

请建议我如何进一步改进此逻辑,谢谢。

最佳答案

听起来像是一个简单的 Map 练习:

data.frame(Map(function(d,l,h) d < l | d > h, Data, data_1, data_2))
#     A     B    C     D
#1 TRUE  TRUE TRUE  TRUE
#2 TRUE FALSE TRUE FALSE
#3 TRUE  TRUE TRUE  TRUE
#4 TRUE FALSE TRUE FALSE
#5 TRUE FALSE TRUE FALSE
#6 TRUE  TRUE TRUE  TRUE
#7 TRUE FALSE TRUE FALSE
#8 TRUE  TRUE TRUE  TRUE

如果您想要 0/1 输出,只需将逻辑比较包装在 as.integer 中:

data.frame(Map(function(d,l,h) as.integer(d < l | d > h), Data, data_1, data_2))

如果您的数据是 matrix 对象开始,您可以使用 sweep:

sweep(Data, 2, data_1, FUN=`<`) | sweep(Data, 2, data_2, FUN=`>`)
#        A     B    C     D
#[1,] TRUE  TRUE TRUE  TRUE
#[2,] TRUE FALSE TRUE FALSE
#[3,] TRUE  TRUE TRUE  TRUE
#[4,] TRUE FALSE TRUE FALSE
#[5,] TRUE FALSE TRUE FALSE
#[6,] TRUE  TRUE TRUE  TRUE
#[7,] TRUE FALSE TRUE FALSE
#[8,] TRUE  TRUE TRUE  TRUE

关于r - 优化 R 中的 Apply() While(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44959588/

相关文章:

python - 使用python翻转数组中的位

bash - 存储命令的输出,同时还使用 if 语句的退出状态

android - 开始另一个 Activity 时取消所有计时器

r - 使用knitr在附录中显示代码

r - 当多个参数匹配时,如何在单个参数上使用@inheritParams?

r - 从 R 中的文本中提取字符级 n-gram

javascript - 我需要删除 dom 片段还是垃圾收集器会删除它们?

python - Pandas 聚合然后得到组平均值

java - 图布局 : re-layout preserving the shape of the drawing

algorithm - 代码片段的复杂性