LoginSignup
2
0

More than 5 years have passed since last update.

readr::write_csvでcsvを出力すると数字が指数表記になる原因と対策

Last updated at Posted at 2018-05-14

事象

タイトルの通り。

入力
df <- data.frame(
  n = c(1, 10, 1000, 10000)
)
readr::write_csv(df, "tmp.csv")
cat(scan("tmp.csv", character()), sep = "\n")
出力
Read 5 items
n
1
10
1e3
1e4

何も考えずインデックスをデータフレームに含めたりすると、1000が1e3になってしまうので困る場合がある。これはwrite.csv()では発生しない。

ちなみに、このようにして書き込まれたものをreadr::read_csv()で読み込む際には比較的空気を読んでくれるが、トラブる場合もある(cf. r - write_csv read_csv with scientific notation after 1000th row - Stack Overflow)

原因

これは型がdoubleだと発生する。

入力
typeof(df$n)
出力
[1] "double"

対策

明示的にint型として整数を入力するか、as.integer()で変換すれば良い。

入力
df <- data.frame(
  n = c(1, 10, 1000, 10000),
  m = c(1L, 10L, 1000L, 10000L),
  l = as.integer(c(1, 10, 1000, 10000))
)
readr::write_csv(df, "tmp.csv")
cat(scan("tmp.csv", character()), sep = "\n")
出力
Read 5 items
n,m,l
1,1,1
10,10,10
1e3,1000,1000
1e4,10000,10000
入力
str(df)
出力
'data.frame':   4 obs. of  3 variables:
 $ n: num  1 10 1000 10000
 $ m: int  1 10 1000 10000
 $ l: int  1 10 1000 10000
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0