11

I have a dataframe and want to determine for a given column if every value in the column is equal to zero.

This is the code I have:

z <- read.zoo(sub, sep = ",", header = TRUE, index = 1:2, tz = "", format = "%Y-%m-%d %H:%M:%S")

if(all.equal(z$C_duration, 0)) 
  C_dur_acf = NA

But I am getting an error:

 Error in if (all.equal(z$C_duration, 0)) { : 
  argument is not interpretable as logical

The code should return a boolean value (TRUE/FALSE) if the entire column is all zeros.

T.Grover
  • 189
  • 2
  • 2
  • 8
  • 1
    Welcome to SO. First of all you should read [here](http://stackoverflow.com/help/how-to-ask) about how to ask a good question; a good question has better chances to be solved and you to receive help. On the other hand a read of [this](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) is also good. It explains how to create a reproducible example in R. Help users to help you by providing a piece of your data a desired output and things you have tried so far. – SabDeM Oct 24 '16 at 21:04
  • `z` is a zoo object, not a data.frame. – G. Grothendieck Oct 24 '16 at 21:16
  • @G.Grothendieck Yes you're right. In this case I don't believe it matters because dataframe and zoo object columns can be indexed in the same manner using the '$' operator – T.Grover Oct 24 '16 at 23:31

3 Answers3

12

Use all builtin: all(z$C_duration == 0)

Steves
  • 2,798
  • 21
  • 21
3

Here is an example by using the iris dataset built in R and apply function in addiction with all that allows you to test if all elements of the objects you pass in it do respect one or more logical conditions.

Do note that in this case the "objects" is a column of the data frame. The code with lapply do the same for every column.

lapply(iris[-5], function(x) all(x == 0))
$Sepal.Length
[1] FALSE

$Sepal.Width
[1] FALSE

$Petal.Length
[1] FALSE

$Petal.Width
[1] FALSE
SabDeM
  • 7,050
  • 2
  • 25
  • 38
0

To use all.equal:

if(all.equal(z$C_duration, rep(0, length(z$C_duration)){
    C_dur_acf = NA
}

In essence all.equal does a pair-wise test. The if statement is failing because all.equal(z$C_duration,0) returns: "Numeric: lengths (##, 1) differ"

HTH!

emilliman5
  • 5,816
  • 3
  • 27
  • 37