13

I have a situation where I need to test whether a variable is factor(0) but any logical test (including comparing to NULL) I try to assign to it gives logical(0). How do I test if something is an empty factor?

edit: allow me to elaborate.

I have a function and it looks at the attribute of the vector that it takes in, but not every vector has that the attribute, so for vectors that don't have the attribute, when I query the attribute attr(vector,"attribute") my return is factor(0) but when I compare that to 0 I get logical(0) and comparing it to null or NA also won't work. Any ideas?

6
  • 4
    factor(0) is not an empty factor. You've created a factor of the number zero with one level.... What are you trying to do? Commented Aug 20, 2015 at 14:35
  • identical(x, factor(0)) to test if an object is a factor with number zero. Not sure if that is what you are really looking for though
    – Whitebeard
    Commented Aug 20, 2015 at 14:36
  • I have edited the question hopefully I am being clearer now
    – Carl
    Commented Aug 20, 2015 at 14:55
  • 2
    if (length(x)){...} will evaluate ... if and only if x is nonempty... Commented Aug 20, 2015 at 15:06
  • Are you using the attr function correctly? I think the problem is you are managing to do something that returns without an error, but isn't returning what you expect. look at '?attr' Commented Aug 20, 2015 at 15:10

2 Answers 2

13

I was able to use length==0 thanks for the help

1
  • 3
    Note that as.logical(3) is the same as as.logical(1) is the same as TRUE, so you don't need to force to logical with ==0 or ==F. if your if statement is simply if (length(x)) it will still work. Commented Aug 20, 2015 at 21:23
2

rlang::is_empty() also does the job to find if the object is an empty vector or NULL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.