Andrew
Andrew

Reputation: 3892

How to Drop a Row in R Based on the First Column

I have a data.frame setup like this:

df <- data.frame(units = c(1.5, -1, 1.4),
              what =  c('Num1', 'Num2', 'Num3'))

Which gives me something like this:

  units         what
1 1.500000     Num1
2 -1000000      Num2
3  1.400000      Num3

I want to able to remove the entire row if the number in the first column is -1. So Ideally loop through the whole dataframe and remove the rows that have -1 in the unit column. I've been trying things like this:

if(CONDITION TO REMOVE) {
    print("deleting function...")
    df <- df[-c(df[,'Num2']),]
  }

But it deletes everything in the rest of the df. I only want to delete that one row (and the entire row).

Thanks in advance.

Upvotes: 0

Views: 309

Answers (2)

akash87
akash87

Reputation: 3994

You can use dplyr to better suit your needs:

df.new <- df %>% filter(units != -1) 

Or you can do this using base R

df.new <- df[df$units != -1, ]

Upvotes: 0

dvarelas
dvarelas

Reputation: 988

newdf <- df[-which(df[,1] ==-1),]

newdf is df without the rows containing -1 in the first column.

Upvotes: 1

Related Questions