Home > Software design >  How to verify if when a column is NA the other is not?
How to verify if when a column is NA the other is not?

Time:04-04

I have a dataframe with two columns. I need to check if where a column is NA the other is not. Thanks

Edited.

I would like to know, for each row of the dataframe, if there are rows with both columns not NA.

CodePudding user response:

You can use the following code to check which row has no NA values:

df <- data.frame(x = c(1, NA),
                 y = c(2, NA))

which(rowSums(is.na(df))==ncol(df))

Output:

[1] 1

As you can see the first rows has no NA values so both columns have no NA values.

CodePudding user response:

Here's a simple code to generate a column of the NA count for each row:

x <- sample(c(1, NA), 25, replace = TRUE)
y <- sample(c(1, NA), 25, replace = TRUE)
df <- data.frame(x, y)

df$NA_Count <- apply(df, 1, function(x) sum(is.na(x)))
df
    x  y NA_Count
1  NA  1        1
2  NA NA        2
3   1 NA        1
4   1 NA        1
5  NA NA        2
6   1 NA        1
7   1  1        0
8   1  1        0
9   1  1        0
  •  Tags:  
  • r
  • Related