Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove rows with any zero value

Tags:

r

dplyr

zero

rows

I have a problem to solve how to remove rows with a Zero value in R. In others hand, I can use na.omit() to delete all the NA values or use complete.cases() to delete rows that contains NA values.

Is there anyone know how to remove rows with a Zero Values in R?

For example :

Before

|    DateTime      | Mac1  | Mac2  | Mac3  | Mac4  | ---------------------------------------------------- | 2011-04-02 06:00 | 20    | 0     | 20    | 20    |   | 2011-04-02 06:05 | 21    | 21    | 21    | 21    |   | 2011-04-02 06:10 | 22    | 22    | 22    | 22    |   | 2011-04-02 06:15 | 23    | 23    | 0     | 23    |   | 2011-04-02 06:20 | 24    | 24    | 24    | 24    |  | 2011-04-02 06:25 | 0     | 25    | 25    | 0     |  

After

|    DateTime      | Mac1  | Mac2  | Mac3  | Mac4  | ---------------------------------------------------- | 2011-04-02 06:05 | 21    | 21    | 21    | 21    |   | 2011-04-02 06:10 | 22    | 22    | 22    | 22    |   | 2011-04-02 06:20 | 24    | 24    | 24    | 24    |   
like image 734
YougyZ Avatar asked Apr 02 '12 13:04

YougyZ


People also ask

How do I remove rows with zeros in a DataFrame?

Remove rows with all zeros using ~ operator We can use ~ for specifying a condition i.e. if rows are equal to 0. where, df is the input dataframe and the Parameters of loc[] attribute are: axis = 1 specifies the row position. ~(df !=

How do I remove cells that contain 0 in Excel?

Click "Excel Options" Click "Advanced" Scroll down to "Display options for this worksheet" Untick the box "Show a zero in cells that have zero value"


2 Answers

I would do the following.

Set the zero to NA.

 data[data==0] <- NA  data 

Delete the rows associated with NA.

 data2<-data[complete.cases(data),] 
like image 28
morteza Avatar answered Sep 28 '22 04:09

morteza


There are a few different ways of doing this. I prefer using apply, since it's easily extendable:

##Generate some data dd = data.frame(a = 1:4, b= 1:0, c=0:3)  ##Go through each row and determine if a value is zero row_sub = apply(dd, 1, function(row) all(row !=0 )) ##Subset as usual dd[row_sub,] 
like image 121
csgillespie Avatar answered Sep 28 '22 04:09

csgillespie