【发布时间】:2017-07-06 22:02:34
【问题描述】:
以下数据用于进行比较分析。我使用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() 这样的递归分析一起使用是一个很大的问题。
请建议我如何进一步改进此逻辑,谢谢。
【问题讨论】:
-
你能解释一下你的代码试图做什么吗?我可以运行该函数,但我不确定输出与什么相关。
-
@thelatemail - 将输出存储在
finalData中,将Data中的每个元素与较低阈值data_1和较高阈值data_2进行比较,结果为真假。 -
finalData <- sapply(1:4, function(col) (Data[,col] < data_1[,col] | Data[,col] > data_2[,col]))怎么样 -
第 3 行和第 8 行仍然出错
-
只嵌入
as.integer()
标签: r algorithm optimization packages