0

I'm trying to bind together two dfs..df3 <- rbind(df1, df2).. where df1 and df2 are very similar, except that one has column classes of multiple types (numeric, logical, date, character) and the other df2 has essentially the same elements but all the classes are character.

After rbind()ing, the new df3 has all character classes. But, I want the new df3 to retain (or regain) the classes from df1 (with numeric, logical, date.. classes)

What is the best way to either retain column classes during rbind(), or re-assign column classes after the rbind()? ..Using the classes from another similarly-structured df?

I've seen the for-loop semi-solution here: I would like to reassign 128 column classes with a list/vector of column classes?

But it is complicated (to me) and doesn't involve rbind() or rbindlist()

example df

df1 <- tibble(
  a = c(1,2,3,4),
  b = c(TRUE, FALSE, FALSE, TRUE),
  d = c('hi', 'thanks', 'for', 'helping')
)

similar df1, but all characters

df1_char <- map_dfr(df1, as.character) 

bind the original df and character df

bound_df <- rbind(df1, df1_char)

now the bound_df is character, but I want the class types from df1

bound_df  

How can bound_df to have the same column classes as df1?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
NicoWheat
  • 2,157
  • 2
  • 26
  • 34
  • Can't you just use type.convert on df2? – Roland Feb 17 '19 at 09:00
  • 1
    It is stated in `?rbind` that "The type of a matrix result determined from the highest type of any of the inputs in the hierarchy raw < logical < integer < double < complex < character < list .". Therefore, `rbind()` will always coerce your data to character. – tmfmnk Feb 17 '19 at 09:15
  • @Roland Yes, thank you luckily that did solve my problem! – NicoWheat Feb 24 '19 at 01:16

0 Answers0