Stat Stat - 3 months ago 6
R Question

Multiply constant in R

I have vector of numeric with 5 decimal points, I tired to multiply by 7, the result give me integer, I don't know why decimals disappeared. Do you know what happened?

Here is data

> df
ID Begin End Int
1 34 30-Dec-05 15-Jan-06 6.142857
2 66 3-Apr-06 7-Aug-06 13.000000
3 66 28-Feb-06 3-Apr-06 17.857143
4 104 31-Jan-06 28-Feb-06 6.000000
5 104 28-Feb-06 23-May-06 10.000000
6 104 24-May-06 7-Sep-06 22.142857
7 182 9-May-06 10-Jul-06 -1.571429
8 189 10-Apr-06 11-Apr-06 15.285714
9 189 12-Apr-06 12-Apr-06 15.571429
10 189 13-Apr-06 15-Apr-06 15.714286
11 189 13-Aug-06 13-Sep-06 23.428571
12 189 6-Jun-06 6-Jun-06 33.142857
13 193 17-Mar-06 24-Mar-06 2.428571
14 193 27-Jun-06 28-Jun-06 17.000000
15 193 7-Jul-06 25-Sep-06 18.428571
16 237 10-Feb-06 15-Mar-06 -2.000000
17 237 15-Mar-06 10-Apr-06 2.714286
18 264 25-Jan-06 7-Nov-06 -2.285714
19 282 19-Nov-05 1-Aug-06 6.000000

df$cal <- df$Int*7


It gives me

[1] 43 91 125 42 70 155 -11 107 109 110
[11] 164 232 17 119 129 -14 19 -16 42

Answer

R adjusts the print format according to the decimal part of the number; it doesn't necessarily print all the zeros after the decimal point.

> (x = 18/7)
[1] 2.571429
> x*7
[1] 18
> sprintf("%1.10f",x*7)
[1] "18.0000000000"

Based on your example, that's exactly what's happening here: your Int values are all exact multiples of 1/7 (presumably derived from some sort of conversion from units of days to weeks), so multiplying by 7 gives you floating-point results with exact or nearly-exact decimal parts of .00000...

Comments