[英]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))
}
}
}
代码完美运行,但在较大的数据集上有点慢。 我想通过使用apply或outer family 来提高速度。 问题是:
带数据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.