teteh May
teteh May

Reputation: 455

Finding Index from Vector/Matrix or Dataframe in R

I have data in R as follow:

data <- c(1,12,22,0,8,1,0,0)

Is there any way to index the data to find the index for element that is greater than 0? So the result will be:

1 2 3 5 6

I tried to use as.factor(data), but it will take several more step to get the result that I aim for. Thanks.

Upvotes: 1

Views: 39

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101024

Another option is using seq_along (but not as straightforward as the which method by @akrun)

> seq_along(data)[data>0]
[1] 1 2 3 5 6

Upvotes: 0

akrun
akrun

Reputation: 886938

We can use which on a logical vector

which(data >0)
#[1] 1 2 3 5 6

Upvotes: 2

Related Questions