简体   繁体   English

从向量/矩阵或 R 中的 Dataframe 中查找索引

[英]Finding Index from Vector/Matrix or Dataframe in R

I have data in R as follow:我在 R 中有如下数据:

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?有没有办法索引数据以找到大于 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.我尝试使用 as.factor(data),但要获得我想要的结果还需要几个步骤。 Thanks.谢谢。

We can use which on a logical vector我们可以在逻辑vector上使用which

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

Another option is using seq_along (but not as straightforward as the which method by @akrun )另一种选择是使用seq_along (但不像@akrunwhich方法那么简单)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM