0

I have 2 dataframes with exactly similar columns.

Except that the data type definitions are not.

I want to ensure that both dataframes share similar data types.

For example, let's assume only 1 column for both dataframes.

Dataframe_A
KPI
10
144
14
..

Dataframe_B
KPI
10
144
14
..

Both dataframes have the same column which is KPI.

However KPI from Dataframe A is defined as string but KPI from Dataframe B is defined as numeric.

I have hundreds of columns.

Is there a faster way than redefining the column type one by one?

I want to use one of the dataframe as reference. For example Dataframe B should follow Dataframe A column types.

Thanks!

Current solution is not ideal, as I need to define all the columns one by one.

Afiq Johari
  • 1,372
  • 1
  • 15
  • 28
  • Without a reproducible example, it is not clear. May be a hacky option is `rbind` (but also depends on what the types of the datasets are) `rbind(df1[1,], df2)[-1,]`. (assuming they have the same column names and in the same order). Also, if the types are based on the values of the dataset, an easier option is `type.convert(df2)` – akrun Sep 07 '19 at 03:58
  • 1
    Another option that could be useful is `df1[] <- Map(as, df1, Class = lapply(df2, class)) ` – akrun Sep 07 '19 at 04:09
  • hi @akrun, I've updated with some examples. Hope it's clearer :) – Afiq Johari Sep 07 '19 at 04:36
  • This might be helpful https://stackoverflow.com/questions/27361081/r-assign-or-copy-column-classes-from-a-data-frame-to-another – Juan Sebastian Lozano Sep 07 '19 at 05:11
  • It's not clear to me if you want to detect inconsistencies or trigger a failure, or convert – moodymudskipper Sep 07 '19 at 15:25
  • @Moody_Mudskipper, I just want to ensure both have the same schema. – Afiq Johari Sep 08 '19 at 03:50

0 Answers0