1

这个小代码片段应该循环通过一个排序的数据框。它记录在 aIndex 和 cIndex 列以及 bIndex 和 dIndex 列中有多少连续行具有相同信息。如果它们相同,它会存入计数并在下一次增加它,如果它们不同,它会存入计数并在下一次将其重置为 1。

for (i in 1:nrow(myFrame)) {
  if (myFrame[i, aIndex] == myFrame[i, cIndex] &
    myFrame[i, bIndex] == myFrame[i, dIndex]) {
      myFrame[i, eIndex] <- count
      count <- (count + 1)
  } else {
      myFrame[i, eIndex] <- count
      count <- 1
  }
}

它已经运行了很长时间。我知道我应该尽可能地进行矢量化,但我在这里并没有真正看到它。我应该怎么做才能使这更快?

以下是运行后几行的示例:

aIndex bIndex cIndex dIndex eIndex
     1      2      1      2      1
     1      2      1      2      2
     1      2      4      8      3
     4      8      1      4      1
     1      4      1      4      1
4

2 回答 2

2

也许这会奏效。我已经修改了rlesequence位。

dat <- read.table(text="aIndex bIndex cIndex dIndex
1 2 1 2
1 2 1 2
1 2 4 8
4 8 1 4
1 4 1 4", header=TRUE, as.is=TRUE,sep = " ")
dat$eIndex <-NA
#identify rows where a=c and b=d, multiply by 1 to get a numeric vector
dat$id<-(dat$aIndex==dat$cIndex & dat$bIndex==dat$dIndex)*1
#identify sequence
runs <- rle(dat$id)
#create sequence, multiply by id to keep only identicals, +1 at the end
count <-sequence(runs$lengths)*dat$id+1
#shift sequence down one notch, start with 1
dat$eIndex <-c(1,count[-length(count)])
dat

  aIndex bIndex cIndex dIndex eIndex id
1      1      2      1      2      1  1
2      1      2      1      2      2  1
3      1      2      4      8      3  0
4      4      8      1      4      1  0
5      1      4      1      4      1  1
于 2012-05-21T19:59:39.327 回答
2

我认为这会做你想做的;棘手的部分是计数在差异重置,这实际上使eIndex.

(希望)有一种更简单的方法可以做到这一点,但这就是我想出的。

tmprle <- rle(((myFrame$aIndex == myFrame$cIndex) & 
               (myFrame$bIndex == myFrame$dIndex)))
myFrame$eIndex <- c(1,
                    unlist(ifelse(tmprle$values, 
                                  Vectorize(seq.default)(from = 2,
                                                         length = tmprle$lengths), 
                                  lapply(tmprle$lengths, 
                                         function(x) {rep(1, each = x)})))
                    )[-(nrow(myFrame)+1)]

这使

> myFrame
  aIndex bIndex cIndex dIndex eIndex
1      1      2      1      2      1
2      1      2      1      2      2
3      1      2      4      8      3
4      4      8      1      4      1
5      1      4      1      4      1
于 2012-05-21T17:11:52.480 回答