0

I have two columns, col1 and col2. Col1 can have null values, but col2 can't If col1 has null value, I want to select col2.

I tried this, where data is the dataframe example you see on the image below.

x <- data[is.na(data['col1']), c('col2')]
print(x)

I was expecting it to print the col2 (with 1440), but it prints

integer(0)

Where am I going wrong?

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295
user1960836
  • 1,732
  • 7
  • 27
  • 47
  • 1
    It should be `is.na(data[['col1']])` with double braces. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Please [do not post code or data in images](https://meta.stackoverflow.com/q/285551/2372064) – MrFlick May 08 '23 at 16:56

1 Answers1

0

I don't know if this is exactly what you are looking for but I think the dplyr function coalsesce does what you are looking for:

Given a set of vectors, coalesce() finds the first non-missing value at each position. It's inspired by the SQL COALESCE function which does the same thing for SQL NULLs.

For your example:

coalesce(data$col1, data$col2)

Would return col1 is non-null and col2 if col1 is null.

Andrew Barros
  • 108
  • 1
  • 7