2

I am trying to merge 2 columns one of which is an integer, and the other a double. However, coalesce will not work. I have also tried to use ifelse and it will not work: it converts the double into an integer which is inaccurate.

fd$t9_2_Ext_DV <- (sample.int(101,size=100,replace=TRUE)-1)/100 fd$t9_2_Mod_DV <- (sample.int(101,size=100,replace=TRUE)-1)

    workings_h2_t9 <- fd %>%
    select(c(t9_2_Ext_DV, t9_2_Mod_DV)) %>%
    mutate(DV1 = coalesce(t9_2_Ext_DV, t9_2_Mod_DV),
           con = ifelse(is.na(t9_2_Mod_DV), 0, 1))  %>%
    select(c(DV1, con)) %>% 
    na.omit

Error in mutate_impl(.data, dots) : 
  Vector 1 has type 'double' not 'integer'

A tibble: 6 × 2
  t9_2_Ext_DV t9_2_Mod_DV
        <int>       <dbl>
1          NA          NA
2          NA          NA
3          NA          NA
4          NA          NA
5          NA          NA
6          NA          NA
Caleb
  • 124,013
  • 19
  • 183
  • 272
Lowpar
  • 897
  • 10
  • 31
  • 1
    It would be easier to help you if you provided a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Jul 25 '17 at 18:38
  • @MrFlick edited now to include the production of random vectors one integer one double. – Lowpar Jul 25 '17 at 18:51

1 Answers1

3

Convert the integer column to double with as.numeric(), then coalesce

workings_h2_t9 <- fd %>%
select(c(t9_2_Ext_DV, t9_2_Mod_DV)) %>%
mutate(DV1 = coalesce(as.numeric(t9_2_Ext_DV), t9_2_Mod_DV))  %>%
select(DV1) %>% 
na.omit
Alex P
  • 1,574
  • 13
  • 28
  • Simple, yet elegant, I tried to do it outside of the coalesce, but it did not work, it worked as you suggested :D – Lowpar Jul 25 '17 at 18:53