Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

r - Correct number of decimal places reading in a .csv

I have a .csv where one of the columns contains numbers that have 7 decimal places, e.g.: -117.2403266.

When I'm reading the .csv into R it only ever shows 4 decimal places for that column, e.g.: -117.2403. Or maybe they are all there but when I print it only shows the four decimal places?

I thought that this might be solved within the arguments of the read.csv() function, but it doesn't say anything about decimal places.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

read.csv is not truncating or rounding, but your print.data.frame function is only displaying the values to the precision specified in options(). Try:

 print(dfrm, digits=10)

> dfrm<- data.frame(test=-117.2403266)
> print(dfrm)
       test
1 -117.2403
> print(dfrm, digits=10)
          test
1 -117.2403266

Using format as suggested would show that the precision has not been lost, but it would return a character vector, so it might not be suitable for assignment when a numeric value was expected.

Edit of a 2 yr-old post: This topic might bring up the question regarding how integers can be imported when they are larger than .Machine$integer.max #[1] 2147483647, since such they can now be internally stored exactly as 'numeric'-abscissa values, so that maximum would be 2^52 (or 2^53-1, I forget which it is). When these are read in from a scan-based function (as are all 0f the read.*-family), you would need to declare as 'numeric' rather than 'integer':

> str( scan(text="21474836470", what=integer()))
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  scan() expected 'an integer', got '21474836470'
> str( scan(text="21474836470", what=numeric()))
Read 1 item
 num 2.15e+10
> str( read.table(text="21474836470", colClasses="integer"))
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  : 
  scan() expected 'an integer', got '21474836470'
> str( read.table(text="21474836470", colClasses="numeric"))
'data.frame':   1 obs. of  1 variable:
 $ V1: num 2.15e+10

If you don't specify a type or mode for "what", scan would assume numeric() and it would succeed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...