wasvbbbft dgh
wasvbbbft dgh

Reputation: 53

How to get row index when column equals 1 in R dataframe?

I need to get row numbers in list when dataframe columns equals 1. Example code:

emp.data <- data.frame(
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25),
   start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
      "2015-03-27")),
    column = c(0, 1, 0, 1, 1),
   stringsAsFactors = FALSE
)
emp.data <- tail(emp.data, 3)
emp.data

I tried this:

result <-as.numeric(rownames(emp.data[emp.data$column==1,]))

but i get this output:

4 5

and i need output like this:

2 3

Upvotes: 3

Views: 1703

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 102241

You can try seq_along like below

> with(emp.data, seq_along(column)[column == 1])
[1] 2 3

Upvotes: 1

Duck
Duck

Reputation: 39613

You can reset rownames:

#Code
rownames(emp.data)<-NULL
result <-as.numeric(rownames(emp.data[emp.data$column==1,]))

The fastest and most optimal way would be (many thanks and credits to @RuiBarradas):

#Code2
rownames(emp.data)<-NULL
result <- rownames(emp.data)[emp.data$column == 1]

Upvotes: 3

akrun
akrun

Reputation: 887501

We can use which on a logical expression instead of row.names as row.names can be different

which(emp.data$column == 1)

Upvotes: 5

Related Questions