Home > Enterprise >  R: index-based apply to vector
R: index-based apply to vector

Time:11-07

Given:

original_vector <- c(2, 2, 2, 3)
indices <- c(1, 0, 0, 1)

I want to apply some function to original_vector, but based on indices. e.g. if the function is "increment by 5", my desired output would be [7, 2, 2, 8].

I know how do this with a for-loop but I'd like to use something in the apply family.

There are similar questions, but they seem to be more complicated than my own usecase.

CodePudding user response:

If you want to use something from the apply family, consider mapply and provide both vectors. mapply and the custom function my_fun are taking two arguments: original_vector and indices.

my_fun <- function(vec, indices) {
  vec[indices == 1] <- vec[indices == 1]   5
  vec
}

mapply(my_fun, original_vector, indices)

Output

[1] 7 2 2 8

CodePudding user response:

In dplyr you can do this:

library(dplyr)
data.frame(original_vector, indices) %>%
  mutate(original_vector = ifelse(indices > 0,
                                  original_vector   5,
                                  original_vector))
  original_vector indices
1               7       1
2               2       0
3               2       0
4               8       1
  • Related