Home > other >  How to remove infinite values from dataframe?
How to remove infinite values from dataframe?

Time:02-01

I want to assign Inf values in the dataframe exp as NA.

exp <- as.data.frame(log2(exp))
exp[!is.finite(unlist(exp)),] <- NA

Traceback:

Error in `[<-.data.frame`(`*tmp*`, !is.finite(unlist(exp)), , value = NA) : 
  non-existent rows not allowed

Data:

#> dput(exp[1:3,1:3])
structure(list(TCGA.4A.A93W.01A = c(48.3424, 2.2117, 0), TCGA.A4.7734.01A = c(43.8689, 
1.8499, 50.74), TCGA.A4.7997.01A = c(70.2027, 86.9447, 1.2938
)), row.names = c("A1BG", "A1CF", "A2BP1"), class = "data.frame")

CodePudding user response:

Your example dataframe doesn't have any non-finite values, but if it did, you could do this:

df[abs(df)==Inf] <- NA

Input:

df=data.frame(val1 = c(10, 20, Inf),val2 = c(3, -Inf, Inf))

Output:

  val1 val2
1   10    3
2   20   NA
3   NA   NA

CodePudding user response:

Replacing all values in a frame can be done this way:

expr
#       TCGA.4A.A93W.01A TCGA.A4.7734.01A TCGA.A4.7997.01A
# A1BG          5.595217        5.4551266        6.1334546
# A1CF          1.145156        0.8874473        6.4420262
# A2BP1             -Inf        5.6650516        0.3716146
expr[] <- lapply(expr, function(z) replace(z, !is.finite(z), z[NA][1]))
expr
#       TCGA.4A.A93W.01A TCGA.A4.7734.01A TCGA.A4.7997.01A
# A1BG          5.595217        5.4551266        6.1334546
# A1CF          1.145156        0.8874473        6.4420262
# A2BP1               NA        5.6650516        0.3716146

CodePudding user response:

is.infinite() doesn’t have a method for dataframes, so coerce to a matrix to index:

exp[is.infinite(as.matrix(exp))] <- NA

exp
      TCGA.4A.A93W.01A TCGA.A4.7734.01A TCGA.A4.7997.01A
A1BG          5.595217        5.4551266        6.1334546
A1CF          1.145156        0.8874473        6.4420262
A2BP1               NA        5.6650516        0.3716146

CodePudding user response:

You can do this with {dplyr}

library(dplyr)

d <- structure(list(a = c(1, Inf, Inf, Inf, 2), b = c(Inf, 3, -Inf, -Inf, 3)), class = "data.frame", row.names = c(NA, -5L))

d %>% mutate(across(everything(), ~if_else(is.finite(.x), .x, NA_real_)))
#>    a  b
#> 1  1 NA
#> 2 NA  3
#> 3 NA NA
#> 4 NA NA
#> 5  2  3

Created on 2023-01-31 with reprex v2.0.2

  •  Tags:  
  • r
  • Related