神Hadley R for Data Science の例題たちとその解答を書き残します。
今回はChapter 11 Data importです。
過去の記事
この章ではreadr
ライブラリを使います。
readr
も含めて
library(tidyverse)
を本章での環境とします。
Chapter 11 Data Import
11.2 Getting Started
11.2.2 Exercises
1. What function would you use to read a file where fields were separated with “|”?
read_delim(file, delim = "|")
2. Apart from
file
,skip
, andcomment
, what other arguments doread_csv()
andread_tsv()
have in common?
col_names
, col_types
, locale
, na
, quoted_na
, quote
, trim_ws
, n_max
, n_max
, guess_max
, progress
3. What are the most important arguments to
read_wfw()
?
col_positions
4. Sometimes strings in a CSV file contain commas. To prevent them from causing problems they need to be surrounded by a quoting character, like
"
or'
. By convertion,read_csv()
assumes that the quoting character will be"
, and if you want to change it you’ll need to useread_delim()
instead. What arguments do you need to specify to read the following text into a data frame?"x,y\n1,'a,b'"
read_delim("x,y\n1,'a,b'", delim = ",", quote = "'")
問題文にはread_csv
は使えないとあるが、次のようにすれば普通に使えるように思う。
read_csv("x,y\n1,'a,b'", quote = "'")
5. Identify what is wrong with each of the following inline CSV files. What happens when you run the code?
read_csv("a,b\n1,2,3\n4,5,6") read_csv("a,b,c,\n1,2\n1,2,3,4") read_csv("a,b\n\"1") read_csv("a,b\n1,2\na,b") read_csv("a;b\n1;3")
一つ目。データは3列あるにもかかわらず、列名はa,b
の二つしか指定されていない。この場合の結果は2列のデータになる。
二つ目。列名は3列指定、データ1行目は2列、データ2行目は4列。この場合は列名に合わせて3列のデータを返し、入力されていないデータ1行目3列目はNA
で埋められる。
三つ目。列名は2列指定でデータは1列。よって1行目2列はNA
になる。\"
はダブルクオーテーションのエスケープになるので引用符として解釈される。引用符は閉じられていないためWarningが出る。ダブルクオーテーションはread_csv
の引数quote
のデフォルト設定であるため、csvの引用符として解釈されている。よってa
は文字列ではなく数値になる。
四つ目。1列目は数値、2列目は文字列であるため、すべてのデータは文字列にパースされる。
五つ目。セミコロンが区切り文字のように入力されているが、read_csv
はセミコロンをそのように扱わないため、セミコロンも含めた文字列データとして扱われる。よって一行一列のデータを返し、列名は`a;b`
, 値は文字列1;3
11.3 Parsing a vector
11.3.5 Exercises
1. What are the most important arguments to
locale()
?
locale #function (date_names = "en", date_format = "%AD", time_format = "%AT", # decimal_mark = ".", grouping_mark = ",", tz = "UTC", encoding = "UTF-8", # asciify = FALSE) #{ #(以下略)
これらの引数の中で最も重要なのは地域の文字列を設定するdate_names
ではないか。
日本の場合はdate_names = "ja"
とする。
2. What happens if you try and set
decimal_mark
andgrouping_mark
to the same character? What happens to the default value ofgrouping_mark
when you setdecimal_mark
to “,”? What happens to the default value ofdecimal_mark
when you set thegrouping_mark
to “.”?
decimal_mark
とgrouping_mark
とが一致しているとエラーになる。
parse_double("1,230,000", locale = locale(decimal_mark = ",", grouping_mark=",")) # Error: `decimal_mark` and `grouping_mark` must be different
decimal_mark
が”.”以外の場合grouping_mark
は”.”になる。
grouping_mark
が”.”以外の場合decimal_mark
は”.”になる。
locale #function (date_names = "en", date_format = "%AD", time_format = "%AT", # decimal_mark = ".", grouping_mark = ",", tz = "UTC", encoding = "UTF-8", # asciify = FALSE) #{ #(中略) # if (missing(grouping_mark) && !missing(decimal_mark)) { # grouping_mark <- if (decimal_mark == ".") # "," ## else "." # } # else if (missing(decimal_mark) && !missing(grouping_mark)) { ### decimal_mark <- if (grouping_mark == ".") # "," # else "." # } #(以下略)
3. I didn’t discuss the
date_format
andtime_format
options tolocale()
. What do they do? Construct an example that shows when they might be useful.
たとえば日付が『年月日』で表示されている場合、date_format
を使って次のようにパースする。
parse_date("2018年1月2日", locale = locale(date_format = "%Y年%m月%d日")) #> [1] "2018-01-02"
同様に、時刻も『○時○分』のようなフォーマットで保存されている場合に使える。
4. If you live outside the US, create a new locale object that encapsulates the settings for the types of file you read most commonly.
たとえば次のような感じで。
myloc <- locale( date_names = "ja", date_format = "%Y年%m月%d日", time_format = "%h時%M分%S秒, tz = "Asia/Tokyo" ) parse_date(hoge, locale = myloc)
5. What’s the difference between
read_csv()
andread_csv2
?
read_csv2
はデータの区切り文字として「カンマ」(”,”)の代わりに「セミコロン」(”;”)を使う。
6. What are the most common encodings used in Europe? What are the most common encodings used in Asia? Do some googling to find out.
ググってみたところUsage of character encodings for websitesというものを見つけた。
これによると、2位のISO-8859-1はいわゆるLatin-1というもので西ヨーロッパで用いられる文字コード。
3位のwindows-1251はロシア含めたスラブ系、いわゆるキリル文字。
4位のwindows-1252は西ヨーロッパ文字、Latin-1を包含している。
5位がわれらのShift JISで、6位のGB2312は中国の簡体字。
以上よりUTF-8を除けば、ヨーロッパではISO-8859-1(Latin-1)が一番、アジアではShift-JISが一番といえる。
早くすべてがUTF-8に移行してShift-JISは根絶やしになってほしい。
7. Generate the correct format string to parse each of the following dates and times:
d1 <- "January 1, 2010" d2 <- "2015-Mar-07" d3 <- "06-Jun-2017" d4 <- c("August 19 (2015)", "July 1 (2015)") d5 <- "12/30/14" t1 <- "1705" t2 <- "11:15:10.12 PM"
parse_date(d1, "%B %d, %Y") parse_date(d2, "%Y-%b-%d") parse_date(d3, "%d-%b-%Y") parse_date(d4, "%B %d (%Y)") parse_date(d5, "%m/%d/%y") parse_time(t1, "%H%M") parse_time(t2, "%I:%M:%OS %p")