Finding the index inside a vector satisfying a condition
Use which
and take the first element of the result:
which(b > 0.65)[1]
#[1] 3
Get all positions of elements in STL vector that are greater than a value
Loop std::find_if
, starting from where you stopped last time.
Sample (see it work):
std::vector<size_t> results;
auto it = std::find_if(std::begin(v), std::end(v), [](int i){return i > 5;});
while (it != std::end(v)) {
results.emplace_back(std::distance(std::begin(v), it));
it = std::find_if(std::next(it), std::end(v), [](int i){return i > 5;});
}
First we set up the iterator with the first result. If it's not found, the while loop never executes. Otherwise, the index position is stored (std::distance
is basically a more generic it - std::begin(v)
), and the search continues onward.
Find position of first value greater than X in a vector
# Randomly generate a suitable vector
set.seed(0)
v <- sample(50:150, size = 50, replace = TRUE)
min(which(v > 100))
Get first n indexes fulfilling a condition in r
The rank
function is what you are looking for:
which(rank(x2)<=3 & x2<3)
#[1] 2 3 7
Find the minimum and maximum indices of a list given a condition
Filter the zipped list with its indixes and take the min and the max:
>>> list_A = [0,0,0,1.0,2.0,3.0,2.0,1.0,0,0,0]
>>> filtered_lst = [(x,y) for x,y in enumerate(list_A) if y > 0]
>>> max(filtered_lst)
(7, 1.0)
>>> min(filtered_lst)
(3, 1.0)
If you just need the index, unpack the returned value:
>>> maX,_ = max(filtered_lst)
>>> maX
7
Related Topics
Counting Number of Instances of a Condition Per Row R
How to Get a Barplot with Several Variables Side by Side Grouped by a Factor
How to Set Fixed Continuous Colour Values in Ggplot2
Converting a List of Data Frames into Individual Data Frames in R
Protect/Encrypt R Package Code for Distribution
Rstudio Shiny Error: There Is No Package Called "Shinydashboard"
How to Filter Rows Based on Difference in Dates Between Rows in R
Dt: Dynamically Change Column Values Based on Selectinput from Another Column in R Shiny App
How to Stack Error Bars in a Stacked Bar Plot Using Geom_Errorbar
Can Dplyr Join on Multiple Columns or Composite Key
Reading Multiple CSV Files from a Folder into a Single Dataframe in R
R: How to Get the Week Number of the Month
How to Set the Default Language of Date in R
Assign Value to Group Based on Condition in Column
R: What Do You Call the :: and ::: Operators and How Do They Differ