-1

I have a dataframe:

Type   value1                                           value2            
1    Error: unexpected                                seq warn
2    Warning message                                  excepted action 
3    NA                                               produce values
4    In `[<-.factor`(`*tmp*`, iseq, value = "v1")     values produced 
5    NA                                               rewriting data

i want to fill NAs in column value1 with value in column value2. How could i write that condition? Desired result is:

Type   value1                                           value2            
1    Error: unexpected                                seq warn
2    Warning message                                  excepted action 
3    produce values                                   produce values
4    In `[<-.factor`(`*tmp*`, iseq, value = "v1")     values produced 
5    rewriting data                                   rewriting data
  • Find the rows with NA, then assign value from other column: `df1[ is.na(df1$value1), "value1"] <- df1[ is.na(df1$value1), "value2"]` – zx8754 Nov 09 '20 at 19:30

2 Answers2

1

You can use coalesce :

library(dplyr)
df %>%  mutate(value1 = coalesce(value1, value2))

Or in base R :

transform(df, value1 = ifelse(is.na(value1), value2, value2))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

We can use fcoalesce from data.table

library(data.table)
setDT(df)[, value1 := fcoalesce(value1, value2)]
akrun
  • 874,273
  • 37
  • 540
  • 662