0

There is a df with two columns as follows:

method Value
H2O 10.2
NA 5.4
NA NA

I want to assign the word "H2O" to the method column instead of NA if there is a corresponding value (here is 5.4, but any value) in the Value column. So I want the df to look like this:

method Value
H2O 10.2
H2O 5.4
NA NA

I am looking for a piece of code in R to do this for my entire table.

Ben
  • 25,545
  • 5
  • 21
  • 43

1 Answers1

1
  1. Indexed assignment:

    df$method[is.na(df$method) & !is.na(df$Value)] <- "H2O"
    df
    #   method Value
    # 1    H2O  10.2
    # 2    H2O   5.4
    # 3   <NA>    NA
    
  2. ifelse:

    ifelse(is.na(df$method) & !is.na(df$Value), "H2O", df$method)
    
  3. replace (can be safer than ifelse)

    replace(df$method, is.na(df$method) & !is.na(df$Value), "H2O")
    

(2 and 3 need to be assigned back to the column, of course.)

r2evans
  • 108,754
  • 5
  • 72
  • 122
  • 1
    Thanks r2evans, That is a great help. – Babak Kasraei Jan 27 '21 at 21:57
  • Do you know that the "norm" (etiquette) on StackOverflow is to [accept](https://stackoverflow.com/help/someone-answers) an answer when it answers your question? There is not a rush, please make sure, but when you are certain, please come back and do so. Doing so not only provides a little perk to the answerer with some points, but also provides some closure for readers with similar questions. (And please consider going back to your [previous question](https://stackoverflow.com/q/65747420/3358272) and accepting one of them, too.) Thank you! – r2evans Jan 27 '21 at 21:59
  • @r2evans , why is replace safer tham ifelse? – GuedesBF Jan 27 '21 at 22:47
  • For one, compare `replace(rep(Sys.time(), 2), c(T,F), Sys.time())` with `ifelse(c(T,F), Sys.time(), Sys.time())`. See https://stackoverflow.com/q/6668963/3358272 – r2evans Jan 28 '21 at 01:53