0

How can I subset a dataframe where 2 columns have values?

For example:

A B
1 2
3 
5 6
  8

becomes

A B
1 2
5 6

2 Answers2

2

One easiest way is to use na.omit (if you are targeting NA values). Kindly go through following R code snippet:

> x
   a  b
1  1  2
2  3 NA
3  5  6
4 NA  8
> na.omit(x)
   a b
 1 1 2
 3 5 6

Another way is to use complete.cases as shown below:

> x[complete.cases(x),]
    a b
  1 1 2
  3 5 6

You can also use na.exclude as shown below:

> na.exclude(x)
    a b
  1 1 2
  3 5 6

Hope it works for you!

Saurabh Chauhan
  • 3,161
  • 2
  • 19
  • 46
2
> subset(df, !is.na(df$A) & !is.na(df$B))
> df[!is.na(df$A) & !is.na(df$B),]
> df[!is.na(rowSums(df)),]
> na.omit(df)

all equivalent

Jean
  • 1,480
  • 15
  • 27