 Apr 13, 2018 52,217 views

## 2 answers to this question.

Yes, we can find the index of an element in a vector as follows:
> a <- c(3, 2, -7, -3, 5, 2)
> b <- (a==-7)  # this will output a TRUE/FALSE vector
> c <- which(a==-7) # this will give you numerical value
> a
  3  2 -7 -3  5  2
> b
 FALSE FALSE  TRUE FALSE FALSE FALSE
> c
 3

This is one of the most efficient methods of finding the index of an element in a vector. answered Apr 13, 2018 by
• 3,790 points

The function match works on vectors :

```x <- sample(1:10)
x
#   4  5  9  3  8  1  6 10  7  2
match(c(4,8),x)
#  1 5
```

match only returns the first encounter of a match, as you requested. It returns the position in the second argument of the values in the first argument.

For multiple matching, %in% is the way to go :

```x <- sample(1:4,10,replace=TRUE)
x
#  3 4 3 3 2 3 1 1 2 2
which(x %in% c(2,4))
#   2  5  9 10
```

%in% returns a logical vector as long as the first argument, with a TRUE if that value can be found in the second argument and a FALSE otherwise. answered Dec 12, 2020 by
• 8,910 points

## How to write a custom function which will replace all the missing values in a vector with the mean of values in R?

Consider this vector: a<-c(1,2,3,NA,4,5,NA,NA) Write the function to impute ...READ MORE

+1 vote

## Custom Function to replace missing values in a vector with the mean of values

Try this. lapply(a,function(x){ifelse(is.na(x),mean(a,na.rm = TRUE ...READ MORE

## Slicing a list using an index vector in r

Use index within [] and provide an ...READ MORE

## How do I remove an element from a list by index in R?

Use list[index] = NULL The list value will ...READ MORE

## R function rep() in Python (replicates elements of a list/vector)

Each element of a vector is duplicated ...READ MORE

## How can I avoid the transformation into an atomic vector in a matrix (r programming)

I'm scrambling to come up with a ...READ MORE

+1 vote

## How to count the number of elements with the values in a vector?

Use dplyr function group_by(). > n = as.data.frame(num) > ...READ MORE

## What is the difference between [] and [[]] notations to access the elements of a list or dataframe in R?

R provides 3 basic indexing operators. Refer ...READ MORE

+1 vote