Is there a way get info from the indexing of an old vector when creating a new vector from it

Viewed 46

Let's say I have a vector named ages and I bound the values of a vector to a limit:

# Create vector
ages <- c(1:7427) # This is not what my vector is actually assigned as btw, it has a lot of random floats in reality.

# Set limits
min_HB <- 11.68987
max_HB <- 11.81083

# Limit vector
HB_ages <- sapply(ages, function(y) min(max(y,min_HB),max_HB))

The HB_ages range is from 1 to length(HB_ages), but I would still like to get info on what are the indices of the values from the original vector. Is there a way to do this?

2 Answers

We can stack on a named vector

stack(setNames(HB_ages, ages))

Or with vectorized approach

data.frame(ind = ages, val = pmin(pmax(ages, min_HB), max_HB))

This seems to be a very simple problem to me. Correct me if I am wrong.

Here is your ages vector (slightly modified)

ages <- round(rnorm(100, 32, 15))
ages
  [1] 37 31  2 33 15 20 41 38 71 47 50 40 64 32 54 28 62 38 42 24 39 22 32 29
 [25] 26 27 32 50 33 11 22 15 21  5 43 17 45 51 47 54 15 13 21 29 13 21 33 23
 [49] 40 24 20 36 29 35 42 54 30 53 32 48 39 46 20 62 49 41 35 44 50 56 17 43
 [73] 36 22 38 30 19 14 40 26 27 50 36 32 36 51 41 25 58 45 27 45 30 44  9 29
 [97] 43 19 41  5

and here are your limits:

min_HB <- 11.68987
max_HB <- 11.81083

and this is what you have done:

HB_ages <- sapply(ages, function(y) min(max(y,min_HB),max_HB))

Index is the same order of the values. Just add that order.

cbind(HB_ages, c(1:length(HB_ages)))

The second column is what you need. Correct?

Related