Why does an empty dataframe fail an is.null() test?

后端 未结 3 1166
清歌不尽
清歌不尽 2021-02-02 10:00

please excuse me if my question is quite basic. I created an empty data frame by df <- data.frame() and obviously the data frame is NULL (empty). when I try to

3条回答
  •  温柔的废话
    2021-02-02 10:41

    df is not NULL because it is a data frame and thus has some defined properties. For instance, it has a class. And you can get the number of rows in the data frame using nrow(df), even if the result should happen to be zero. Therefore, also the number of rows is well-defined.

    As fas as I know, there is no is.empty command in base R. What you could do is, e.g., the following

    is.data.frame(df) && nrow(df)==0
    

    This will give TRUE for an empty data frame (that is, one with no rows) and false otherwise.

    The reason for checking is.data.frame first is that nrow might cause an error, if it is applied to anything else than a data frame. Thanks to &&, nrow(df) will only be evaluated if df is a data frame.

提交回复
热议问题