简体   繁体   中英

R for loop gives: Error in if (is.na(x)) return(0) else return(sign(x)) : argument is of length zero

I am looping through a large data set and have isolated some groups that return the error:

Error in if (is.na(x)) return(0) else return(sign(x)) : argument is of length zero

Other posts have suggested that this indicates the existence of NULLs. However,

is.null(block_of_troublesome_data) [1] FALSE

manually inspecting the df does not show any na values either (which makes sense because I previously ran an na.omit() on the whole block.

What am I missing?

additional info: Here is the df that the loop is working on:

data

A tibble: 120 x 11

Groups: ecoregion_code [1]

ecoregion_code loc_major_basin lake_id lake_name sample_date ym doy value_ft season_code season 1 40 7010103 01-0022-00 ISLAND 1999-07-29 1999 7 210 5.610236 2 Summer 2 40 7010103 01-0022-00 ISLAND 2000-06-18 2000 6 170 6.496063 1 Spring 3 40 7010103 01-0022-00 ISLAND 2000-07-04 2000 7 186 6.496063 2 Summer 4 40 7010103 01-0022-00 ISLAND 2000-08-12 2000 8 225 6.496063 2 Summer 5 40 7010103 01-0022-00 ISLAND 2000-08-26 2000 8 239 6.496063 2 Summer 6 40 7010103 01-0022-00 ISLAND 2000-09-16 2000 9 260 6.496063 3 Fall 7 40 7010103 01-0022-00 ISLAND 2001-06-03 2001 6 154 5.511811 1 Spring 8 40 7010103 01-0022-00 ISLAND 2001-06-10 2001 6 161 5.511811 1 Spring 9 40 7010103 01-0022-00 ISLAND 2001-06-17 2001 6 168 4.986877 1 Spring 10 40 7010103 01-0022-00 ISLAND 2001-10-18 2001 10 291 6.496063 3 Fall

... with 110 more rows

and the output of 'if (is.na(x)) return(0) else return(sign(x))'

if (is.na(data)) return(0) else return(sign(data)) Error in Math.data.frame(data) : non-numeric variable in data frame: lake_idlake_namesample_dateseason In addition: Warning message: In if (is.na(data)) return(0) else return(sign(data)) : the condition has length > 1 and only the first element will be used

and

if (length(data)==0) 0 else if is.na(x) 0 else sign(data) Error: unexpected symbol in "if (length(data)==0) 0 else if is.na"

All zero-length vectors are not NULL so you might want to test for length(x) :

# instead of ...
if (is.na(x)) return(0) else return(sign(x))
# try ...
if (length(x)==0) 0 else if is.na(x) 0 else sign(x)
# or equivalently ...
if(length(foo)==0 || is.na(foo)) 0 else sign(foo)

(You may or may not need return(...) here, that's another issue.)

A test case:

foo <- numeric(0)
is.null(foo) # FALSE
if(length(foo)==0) 0 else if(is.na(foo)) 0 else sign(foo)  # 0
if(length(foo)==0 || is.na(foo)) 0 else sign(foo)  # 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM