2017-12-30 4 views
2

의 고정 번호를 건너 뛰는 동안 내가이 벡터를 가지고 말 :추출 요소 요소

나는 그 요소가 발견되면 1. 수를 포함하는 벡터의 첫 번째 요소를 찾으려면
a <- round(runif(100, 0, 1), digits = 0) 

, 3 요소를 건너 뛰고 (1을 포함하더라도) 1을 포함하는 다음 요소를 찾고 1을 찾은 다음 1을 찾은 후 3 요소를 건너 뜁니다.

필자가 원하는 출력은 건너 뛴 요소를 고려한 후 1이 들어있는 첫 번째 요소의 행 번호와 나머지 행 번호가 1 인 행 번호입니다.

답변

0

아마도 while loop?

set.seed(123) 
a <- round(runif(100,0,1), digits =0) 
n <- length(a) 
ind_less_n <- 1 
i <- 1 
index_save <- numeric(n) 
while(ind_less_n){ 
    if(a[i] == 1){ 
    index_save[i] <- 1 
    i <- i + 4 
    } else { 
    i <- i + 1 
    } 
    if(i > n) ind_less_n <- 0 
} 
head(cbind(a, index_save), 20) 
     a index_save 
[1,] 0   0 
[2,] 1   1 
[3,] 0   0 
[4,] 1   0 
[5,] 1   0 
[6,] 0   0 
[7,] 1   1 
[8,] 1   0 
[9,] 1   0 
[10,] 0   0 
[11,] 1   1 
[12,] 0   0 
[13,] 1   0 
[14,] 1   0 
[15,] 0   0 
[16,] 1   1 
[17,] 0   0 
[18,] 0   0 
[19,] 0   0 
[20,] 1   1 

당신은 내가 당신이 루프의 어떤 종류에 의존하지 않고이 작업을 수행 할 수 있다고 생각하지 않습니다 which(index_save == 1)

+0

오른쪽 ... I + 4는 I + 3을 바꿨다. – jrlewi

1

과 행 번호를 추출 할 수 있습니다. 여기에 한 가지 방법이 있습니다. 우리는 모든 것들의 위치 벡터를 얻습니다. 그런 다음 이전과 3 이하의 벡터의 첫 번째 요소를 반복해서 찾아 목록에서 제거합니다. 자신의 predessesor에 너무 가까운 모든 것들을 제거 할 때까지 반복하십시오.

x = which(a==1) 
repeat { 
    to.remove = which(diff(x) <= 3)[1] + 1 
    if (is.na(to.remove)) break 
    x = x[-to.remove] 
} 

는 매우 큰 벡터를 처리하는 경우,이 작업을 수행하는 더 효율적인 방법이 될 수 있으며, 속도가 문제가되는 경우 아마도 RCpp을 고려하십시오.

0

accumulate = TRUE 또는 purrr::accumulate과 같이 사용할 수 있지만 결과와 건너 뛰기 횟수와 같은 별도의 요소가있는 목록을 반복해야합니다. 예 :

library(tidyverse) 
set.seed(47) 

df_ones <- data_frame(a = rbinom(100, 1, .5), # make sample data 
         is_one = a, # initialize result and count 
         count = NA) %>% 
    split(seq(nrow(.))) %>% # split into list of one-row data frames 
    accumulate( # for each sequential pair of elements, return and pass on a list of... 
     ~list(a = .y$a, # the original value for checking, 
       is_one = if(.x$count <= 3) 0 else .y$is_one, # the result, changing 1 to 0 where required, and 
       # the count since a 1, resetting when a 1 is kept 
       count = if(.x$count > 3 & .y$is_one) { 
        1 
       } else { 
        .x$count + 1 
       }), 
     .init = list(a = NA, is_one = 0, count = 4) # set initial .x value 
    ) %>% 
    bind_rows() %>% # collapse resulting list to data frame 
    slice(-1) # remove row for initializing value 

df_ones 
#> # A tibble: 100 x 3 
#>  a is_one count 
#> <int> <dbl> <dbl> 
#> 1  1  1  1 
#> 2  0  0  2 
#> 3  1  0  3 
#> 4  1  0  4 
#> 5  1  1  1 
#> 6  1  0  2 
#> 7  0  0  3 
#> 8  0  0  4 
#> 9  1  1  1 
#> 10  1  0  2 
#> # ... with 90 more rows 

인덱스를 추출하기 위해,

df_ones %>% 
    pull(is_one) %>% # extract result as vector 
    as.logical() %>% # coerce to Boolean 
    which() # get indices of TRUE values 
#> [1] 1 5 9 14 22 29 35 40 44 48 52 56 61 66 71 75 79 84 88 93 97