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
  • 28,684
  • 5
  • 23
  • 45
Babak Kasraei
  • 77
  • 1
  • 6

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
  • 141,215
  • 6
  • 77
  • 149