Can `replace_na` replace NaN values with NA_real_ ?

Hi all,

I have some observations in a dataframe that are NaNs that I want to replace with NA_real_ to run additional calculations. I've found using mutate(var = replace_na(var, NA_real_)) works, but I can't find any documentation for replace_na() saying this should since it is supposed to only replace NA/NA_real_ with another value you specify.

Can someone verify the code under the hood of replace_na() also replaces NaN as well? Or is this just some anomaly that it's working for me.

Best,
Kasey

you can test this for yourself. NaN's are considered NA

> is.na(NaN)
[1] TRUE

Here are some of the functions you requested. In general you can search for them with getAnywhere (and a combination of methods, as replace_na is a method for data.frame)

> getAnywhere(replace_na.data.frame)
A single object matching ‘replace_na.data.frame’ was found
It was found in the following places
  registered S3 method for replace_na from namespace tidyr
  namespace:tidyr
with value

function (data, replace = list(), ...) 
{
    stopifnot(is_list(replace))
    replace_vars <- intersect(names(replace), names(data))
    for (var in replace_vars) {
        check_replacement(replace[[var]], var)
        data[[var]][!is_complete(data[[var]])] <- replace[[var]]
    }
    data
}
<bytecode: 0x0000028478f60e18>
<environment: namespace:tidyr>
> getAnywhere(is_complete)[2]
function (x) 
{
    if (typeof(x) == "list") {
        !vapply(x, is_empty, logical(1))
    }
    else {
        !is.na(x)
    }
}
<bytecode: 0x0000028478ee8b48>
<environment: namespace:tidyr>
3 Likes

Thanks @nirgrahamuk! Yea, my code worked, so I figured, but I know NaN and NA are not exactly the same. But the is.na function gives me confidence here

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.