0 votes
Apr 13, 2018 55,913 views

## 2 answers to this question.

0 votes

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
[1]  3  2 -7 -3  5  2
> b
[1] FALSE FALSE  TRUE FALSE FALSE FALSE
> c
[1] 3

This is one of the most efficient methods of finding the index of an element in a vector.

Transform data into actionable insights with our Data Analytics Course – Enroll today!

answered Apr 13, 2018 by
• 3,790 points
0 votes

The function match works on vectors :

```x <- sample(1:10)
x
# [1]  4  5  9  3  8  1  6 10  7  2
match(c(4,8),x)
# [1] 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
# [1] 3 4 3 3 2 3 1 1 2 2
which(x %in% c(2,4))
# [1]  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

0 votes
1 answer

## 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
2 answers

## 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

0 votes
1 answer

## Slicing a list using an index vector in r

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

0 votes
1 answer

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

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

0 votes
0 answers

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

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

0 votes
0 answers

## 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
2 answers

## 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

0 votes
1 answer

## 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
1 answer

## How to extract every nth element of a vector using R?

m <- 1:50 n<- m[seq(1, length(m), 6)] The above ...READ MORE

0 votes
1 answer

## How can I increase the number of axis ticks in R ?

You can try to override ggplots default ...READ MORE