Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

In R, I have an operation that creates some Inf values when I transform a data frame.

I would like to turn these Inf values into NA values. The code I have is slow for large data, is there a faster way of doing this?

Say I have the following data frame:

dat <- data.frame(a=c(1, Inf), b=c(Inf, 3), d=c("a","b"))

The following works in a single case:

 dat[,1][is.infinite(dat[,1])] = NA

So I generalized it with the following loop

cf_DFinf2NA <- function(x)

{

    for (i in 1:ncol(x)){

          x[,i][is.infinite(x[,i])] = NA

    }

    return(x)

}

But I don't think that this is really using the power of R.

1 Answer

0 votes
by
edited by

To clean ‘Inf’ values from a data frame, you can use the following functions:

Using do.call and replace on the data frame:

dat <- data.frame(a=c(1, Inf), b=c(Inf, 3), d=c("a","b"))

> dat

    a   b d

1   1 Inf a

2 Inf   3 b

> do.call(data.frame,lapply(dat, function(x) replace(x, is.infinite(x),NA)))

   a  b d

1  1 NA a

2 NA  3 b

You can also use the set function from the data.table package which uses references instead of internal copying.

for (j in 1:ncol(dat)) set(dat, which(is.infinite(dat[[j]])), j, NA)

> dat

   a  b d

1  1 NA a

2 NA  3 b

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...