tospig
tospig

Reputation: 8343

r - subsetting one row of data frame drops zero decimal from number

Data

Given a data frame

df <- data.frame("id"=c(1,2,3), "a"=c(10.0, 11.2, 12.3),"b"=c(10.1, 11.9, 12.9))

> df
  id    a    b
1  1 10.0 10.1
2  2 11.2 11.9
3  3 12.3 12.9

> str(df)
'data.frame':   3 obs. of  3 variables:
 $ id: num  1 2 3
 $ a : num  10 11.2 12.3
 $ b : num  10.1 11.9 12.9   

Question

When subsetting the first row, the .0 decimal part from the 10.0 in column a gets dropped

> df[1,]
  id  a    b
1  1 10 10.1

> str(df[1,])
'data.frame':   1 obs. of  3 variables:
 $ id: num 1
 $ a : num 10
 $ b : num 10.1

I 'assume' this is intentional, but how do I subset the first row so that it keeps the .0 part?

Notes

Subsetting two rows keeps the .0

> df[1:2,]
  id    a    b
1  1 10.0 10.1
2  2 11.2 11.9

Upvotes: 1

Views: 60

Answers (1)

Molx
Molx

Reputation: 6931

I assume you understand this is a matter of how the number is printed, and not about how the value is stored by R. Anyway, you can use format to ensure the digits will be printed:

> format(df[1,], nsmall = 1)
   id    a    b
1 1.0 10.0 10.1
> format(df[1,], nsmall = 2)
    id     a     b
1 1.00 10.00 10.10

The reason for this behavior is not about the number of rows being printed. R will try to display the minimum number of decimals possible. But all numbers in a column will have the same number of digits to improve the display:

> df2 <- data.frame(a=c(1.00001, 1), b=1:2)
> df2
        a b
1 1.00001 1
2 1.00000 2

Now if I print only the row with the non-integer number:

> df2[1,]
        a b
1 1.00001 1

Upvotes: 5

Related Questions