简体   繁体   中英

Is there a consistent way to force errors on incorrect list or vector indexing

My expectation from other programming languages is that (1:4)[3:5] and list(asdf = 4, qwerty = 5)$asdg should both raise exceptions. Instead, the first silently returns c(3, 4, NA) , and the second silently returns NULL (as does or list(asdf = 4, qwerty = 5)[[asdg]] ).

While this sort of behavior can occasionally be useful, far more often (in my experience), it turns a minor typo, off-by-one error, or failure to rename a variable everywhere that it's used from a trigger for an immediate and easy-to-debug error, into a trigger for a truly baffling error about 20 (or 200) steps down the line, when the silently propagating NULL s or NA s finally get fed into a function or operation that is loud about them. (Of course, that's still better than the times that it doesn't produce an error at all, just garbage results.)

data.frame()[,'wrong'] gives an error, but data.frame()['wrong',] just returns NA .

What I'm looking for is a way to do vector/array/list/data.frame/etc. subscripting/member access that will reliably cause an error immediately if I use an index that is invalid. For lists, get('wrong', list()) does what I'm looking for, but that can be quite ugly at times (especially if using the result as for subscripting something else). It's usable, but something better would be nice. For vectors (and data.frame rows ), even that doesn't work.

Is there a good way to do this?

I am not sure if you can change this behaviour globally but you can handle them on individual basis as needed based on type of the data.

For example, for vectors -

subset_values <- function(x, ind) {
  if(min(ind) > 0 && max(ind) <= length(x)) x[ind]
  else stop('Incorrect length')
}

subset_values(1:4, 3:5)
#Error in subset_values(1:4, 3:5) : Incorrect length

subset_values(1:4, -1:3)
#Error in subset_values(1:4, -1:3) : Incorrect length

subset_values(1:4, 1:3)
#[1] 1 2 3

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