R “argument is of length zero” in if(condition)

11,486

If data is a one dimension array (the binary data you showed is) rather then a matrix, vector, or other structure you can use length to find the row count. This code shows how to add a count based on matches with a one dimensional array (note I assume inc is a pascal like custom function).

data = c(1, 0, 0, 1, 1, 0)
outcome = c(0, 0, 1, 0, 1, 0)

count <- 0
for (i in 1:length(data))
{
    if(outcome[i]==data[i]) {
        count <- count + 1  #could then do inc(count) for package Hmisc
    }
}
count

If your data is being returned as a matrix of vectors then try this code (same note on Hmisc).:

data <- read.table(text = "
0  1   0   1
0  0   1   1
1  1   0   0
1  0   1   0
0  1   0   1", header = FALSE)
data <- as.matrix(data)

outcome <- c(0, 0, 1, 0, 1)

count <- 0

for (i in 1:nrow(data))
{
    if(!is.null(outcome[i]==data[i, 1])) {
        count <- count + 1  #see first example
    }
}
cat(count)

Note: nrow does return either an integer or NULL

Share:
11,486
sheffy17
Author by

sheffy17

Updated on June 04, 2022

Comments

  • sheffy17
    sheffy17 almost 2 years

    Very new to R, would appreciate if you could tell me what I’m doing wrong.

    This was my initial code:

    count <- 0
    for (i in 1:nrow(data))
    {
        if(outcome[i]==data[1,i])
        inc(count) <- 1  #package Hmisc
    }
    

    where outcome and data[1] are vectors with binary values eg. [1, 0, 0, 1, 1, 0..]

    I got the result ‘argument is of length zero’ with the if statement. Tested it individually with rows that matched/mismatched, discovered that the result shows up only in the latter.

    So I amended my code to:

    count <- 0
    for (i in 1:nrow(data))
    {
        if(!is.null(outcome[i]==data[1,i]))
        inc(count) <- 1  #package Hmisc
    }
    

    Now the value that count returned is the number of ‘for' iterations.

    Doesn’t this mean R is NOT returning a null value for ANY mismatch in the new code?? How is this happening? Solutions please?