0

I want to change the datatype of columns for a dataframe however the numeric columns drop the trailing zeros.

Take example of mtcars:

mtcars


mpg                   cyl  disp  hp  drat wt  qsec  vs     am gear carb
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2

when I change the datatypes of columns:

mtcars[, ] <- lapply(mtcars[, ], as.character)

mpg                   cyl  disp  hp  drat wt  qsec  vs     am gear carb
Mazda RX4             21   6     160 110  3.9 2.62  16.46  0  1    4    4
Mazda RX4 Wag         21   6     160 110  3.9 2.875 17.02  0  1    4    4
...

I was expecting the trailing 0 in disp to be preserved.

Deep
  • 528
  • 3
  • 12
  • 27
  • 2
    The trailing zeroes which are being dropped are not _significant_ digits in any case. Use something like `format()` if you want to print the numerical data as text, with a certain number of decimal places. – Tim Biegeleisen Aug 19 '19 at 13:37
  • I am comparing two data frames and I need to have character columns to compare these.Right now 160.0 is not equal to 160 as per the comparison logic as it is matching both as characters .I cant change this logic so wanted to have the trailing zeros. – Deep Aug 19 '19 at 14:11

0 Answers0