获取值的运行的开始和结束索引

时间:2017-10-26 18:30:37

标签: r sequence

我有一个矢量:

keyword_list = [x.word for x in spark.read.load(file).collect()]
keep_words_udf = udf(lambda word_list: [ word for word in word_list if word in keyword_list], ArrayType(StringType()) )

我想获得每次运行相等值的开始和结束索引:

a <- c(1, 1, 0, 0, 1, 2, 0, 0)

3 个答案:

答案 0 :(得分:12)

来自基地R的解决方案。

a <- c(1,1,0,0,1,2,0,0)

# Get run length encoding
b <- rle(a)

# Create a data frame
dt <- data.frame(number = b$values, lengths = b$lengths)
# Get the end
dt$end <- cumsum(dt$lengths)
# Get the start
dt$start <- dt$end - dt$lengths + 1

# Select columns
dt <- dt[, c("number", "start", "end")]
# Sort rows
dt <- dt[order(dt$number), ]

dt
#  number start end
#2      0     3   4
#5      0     7   8
#1      1     1   2
#3      1     5   5
#4      2     6   6

更新

这是一个使用with来使代码更简洁的解决方案。

with(rle(a), data.frame(number = values,
                        start = cumsum(lengths) - lengths + 1,
                        end = cumsum(lengths))[order(values),])
#  number start end
#2      0     3   4
#5      0     7   8
#1      1     1   2
#3      1     5   5
#4      2     6   6

答案 1 :(得分:2)

使用dplyr

中的rleiddata.table
library(data.table)
library(dplyr)
a=c(1,1,0,0,1,2,0,0)
df=data.frame(number=c(1,1,0,0,1,2,0,0))
df$Id=data.table::rleid(df$number)
df$rowname=seq(1:length(a))
df%>%group_by(Id,number)%>%summarise(start=first(rowname),end=last(rowname))%>%arrange(number)

# Groups:   Id [5]
     Id number start   end
  <int> <dbl> <int> <int>
1     2     0     3     4
2     5     0     7     8
3     1     1     1     2
4     3     1     5     5
5     4     2     6     6

答案 2 :(得分:1)

在基础R中使用for循环的解决方案:

a <- c(1, 1, 0, 0, 1, 2, 0, 0)

start <- 1
res <- data.frame()
v <- c(a, -1) # add number that is different from all other numbers

for (index in 1:(length(v) - 1)) {
  if (v[index] != v[index + 1]) {
    res <- rbind(res, 
                 data.frame(element = v[index], start = start, stop = index))
    start <- index + 1
  }
}

给出了:

  element start stop
1       1     1    2
2       0     3    4
3       1     5    5
4       2     6    6
5       0     7    8