Lowpar
Lowpar

Reputation: 907

Merge a column with an integer and a double together in r

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

Upvotes: 2

Views: 1338

Answers (1)

Alex P
Alex P

Reputation: 1494

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

Upvotes: 3

Related Questions