Home > Net >  Create a list of names/indices of overlapping fragments of vector based on condition [R]
Create a list of names/indices of overlapping fragments of vector based on condition [R]

Time:03-21

I want to perform a sliding window analysis of a long vector in R. Doing so, I would like to check, whether given fragments of this vector contain certain value.

Below I paste a reproducible example. This vector (vctr) contains 77 elements (either 0 or 1). I am analyzing it with sliding window encompassing 10 items (segment) with overlap encompassing 5 elements (overlap).

I know how to check, whether given fragment contains certain value (in this case 1) or not (split_vctr). However I would also like to do something else, namely:

I would like to create a new variable (list or vector) containing only indices of those fragments, which fulfill the given criterion (in this case: which contain at least one value equal to 1; in this case: TRUE).

Let's suppose that the initial list would be named - how could I extract only the names of fragments which are TRUE?

I would highly appreciate your help.

Dummy data:

# dummy vector
vctr <- c(rep(0, 11), rep(1, 4), rep(0, 25), rep(1, 3), rep(0, 31),rep(1, 3))

# split parameters:
segment <- 10 # length of each segment
overlap <- 5 # length of each overlapping part

#finding coordinates
start_coordinates <- seq(1, length(vctr), by=segment-overlap)
end_coordinates   <- start_coordinates   segment - 1

#check whether splitted vector fragments meet a condition
split_vctr <- lapply(1:length(start_coordinates), function(i) 1 %in% vctr[start_coordinates[i]:end_coordinates[i]])

CodePudding user response:

which(unlist(split_vctr))

will return the indices of split_vctr where it is TRUE

If split_vctr itself was named, you could use these indices to extract the names of the TRUE fragments like this:

names(split_vctr)[which(unlist(split_vctr))]

  • Related