繁体   English   中英

R double for 循环:外部还是应用?

[英]R double for loop: outer or apply?

我有以下代码:

a <- c(1,2,2,3,4,5,6)
b <- c(4,5,6,7,8,8,9)
data <- data.frame(cbind(a,b))
trial <- copy(data)
for (j in 1: ncol(trial)) {
  for (i in 2: nrow(trial)) {
  if (trial[i,j] == trial[i-1,j] & !is.na(trial[i,j]) & !is.na(trial[i-1,j]))  {
     trial[i,j] <- trial[i-1,j] + (0.001*sd(trial[,j], na.rm = T))
    }
 }
}

代码完美运行,但在较大的数据集上有点慢。 我想通过使用applyouter family 来提高速度。 问题是:

  1. 我知道如何使用 apply 应用单个循环,但不是 2,尤其是在这种情况下,我需要根据案例特定条件替换单个值,用另一个单个值(滞后)加上标准的乘数偏差(这是我需要在整个列上计算的东西;
  2. 除了这个已解决的问题,我完全没有使用外部和向量化函数而不是循环的经验。

带数据data.table

library(data.table)
f <- function(x)ifelse(x==shift(x), x + 0.001* sd(x, na.rm = TRUE), x)
setDT(data)[, lapply(.SD, f), ]

dplyr

library(dplyr)
f <- function(x)ifelse(x==lag(x), x + 0.001* sd(x, na.rm = TRUE), x)
data %>%
  mutate_each(funs(f))

这对你有用吗?

a <- c(1,2,2,3,4,5,6)
b <- c(4,5,6,7,8,8,9)
data <- data.frame(cbind(a,b))
trial <- data.frame(a,b)
for (j in 1: ncol(trial)) {
# Finds matching rows and add a single row shift in the results
# (diff returns n-1 elements and we want n elements) 
  matching<-!c(TRUE, diff(trial[,j]))
  trial[matching,j]<- data[matching,j]+(0.001*sd(trial[,j], na.rm = T))
}

我对内部循环进行了矢量化,这应该对性能有显着提高。 如果有多个匹配的行,我没有测试 sd 计算会发生什么。
我会把它留给其他人来改进这个修订版。 使用 data.table 可以带来额外的好处。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM