Combining Subjects in R / Recoding NA

I have two lists (from a multi-wavelength review) that look like this:

X1 X2
1  NA
NA  2
NA  NA

How can I easily combine this into a third element, where the third column always takes the non-NA value of column X1 or X2 and encodes NA when both values ​​are equal to NA?

+3
source share
4 answers

Combining the use of Gavin withinand the use of Prasad ifelsegives us a simpler answer.

within(df, x3 <- ifelse(is.na(x1), x2, x1))

Multiple calls are ifelsenot needed - if both values NA, you can simply take one of the values ​​directly.

+5
source

Another way ifelse:

df <- data.frame(x1 = c(1, NA, NA, 3), x2 = c(NA, 2, NA, 4))
> df
  x1 x2
1  1 NA
2 NA  2
3 NA NA
4  3  4

> transform(df, x3 = ifelse(is.na(x1), ifelse(is.na(x2), NA, x2), x1))
  x1 x2 x3
1  1 NA  1
2 NA  2  2
3 NA NA NA
4  3  4  3
+3
source

- X1, X2 NA, :

foo <- function(x) {
    if(all(nas <- is.na(x))) {
        NA
    } else {
        x[!nas]
    }
}

We use the function foo, applying it to each row of your data (here I have data in an object with a name dat):

> apply(dat, 1, foo)
[1]  1  2 NA

So this gives us what we want. To enable this inside your object, we do the following:

> dat <- within(dat, X3 <- apply(dat, 1, foo))
> dat
  X1 X2 X3
1  1 NA  1
2 NA  2  2
3 NA NA NA
+2
source

You did not say what you wanted to do when both were real numbers, but you can use pmax or pmin with the na.rm argument:

 pmax(df$x1, df$x2, na.rm=TRUE)
# [1]  1  2 NA  4
0
source

Source: https://habr.com/ru/post/1784742/


All Articles