# 16章 ベクトル

# 「nhn-techorus.datascienceteam / bookreading · GitLab」 https://gitlab.com/nhn-techorus.datascienceteam/bookreading
# 「personal/sakai · master · nhn-techorus.datascienceteam / bookreading · GitLab」 https://gitlab.com/nhn-techorus.datascienceteam/bookreading/tree/master/personal/sakai
# 「R for Data Science」 http://r4ds.had.co.nz/vectors.html
# 「r4ds-exercise-solutions/vectors.Rmd at master · jrnold/r4ds-exercise-solutions」 https://github.com/jrnold/r4ds-exercise-solutions/blob/master/vectors.Rmd
# 「R for Data Science Solutions」 https://jrnold.github.io/r4ds-exercise-solutions/vectors.html

# 「RPubs - r4ds_ch16」 http://rpubs.com/tocci36/r4ds_ch16

# 16.1 はじめに p257

# 「hadley/lazyeval: Lazy evaluation: an alternative to non-standard evaluation (NSE) for R」 https://github.com/hadley/lazyeval

# 16.1.1 用意するもの
# purrrパッケージの関数をいくつか使います
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 3.3.3
## -- Attaching packages ---------------------------------- tidyverse 1.2.1 --
## √ ggplot2 2.2.1     √ purrr   0.2.4
## √ tibble  1.3.4     √ dplyr   0.7.4
## √ tidyr   0.7.2     √ stringr 1.2.0
## √ readr   1.1.1     √ forcats 0.2.0
## Warning: package 'tibble' was built under R version 3.3.3
## Warning: package 'tidyr' was built under R version 3.3.3
## Warning: package 'readr' was built under R version 3.3.3
## Warning: package 'purrr' was built under R version 3.3.3
## Warning: package 'dplyr' was built under R version 3.3.3
## Warning: package 'stringr' was built under R version 3.3.3
## Warning: package 'forcats' was built under R version 3.3.3
## -- Conflicts ------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
# 16.2 ベクトルの基本

# アトミックベクトル
#   論理、整数、実数、文字、複素数、バイナリの6種類がある。整数ベクトルと実数ベクトルは
#   合わせて数値ベクトルと言う。
# リスト
#   他のリストを要素に含めることができるので再帰ベクトルと呼ぶこともある。

library(magick)
## Warning: package 'magick' was built under R version 3.3.3
## Linking to ImageMagick 6.9.9.14
## Enabled features: cairo, freetype, fftw, ghostscript, lcms, pango, rsvg, webp
## Disabled features: fontconfig, x11
image_read("http://r4ds.had.co.nz/diagrams/data-structures-overview.png")

# すべてのベクトルには、次の2つの特性があります。
# ● typeof()で型がわかる。
typeof(letters)
## [1] "character"
#> [1] "character"
typeof(1:10)
## [1] "integer"
#> [1] "integer"
# ● length()で長さがわかる。
x <- list("a", "b", 1:10)
length(x)
## [1] 3
# 強化ベクトル: augmented vectors

# 16.3 アトミックベクトルで重要な型

# 16.3.1 論理ベクトル
1:10 %% 3 == 0
##  [1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE
c(TRUE, TRUE, FALSE, NA)
## [1]  TRUE  TRUE FALSE    NA
# 16.3.2 数値ベクトル
typeof(1)
## [1] "double"
typeof(1L)
## [1] "integer"
1.5L
## [1] 1.5
x <- sqrt(2) ^ 2
x
## [1] 2
x - 2
## [1] 4.440892e-16
c(-1, 0, 1) / 0
## [1] -Inf  NaN  Inf
# is.finite(), is.infinite(), is.nan(), is.na()

# 16.3.3 文字ベクトル

# Rはグローバル文字列プールを使います。すなわち、ユニークな文字列が一度だ
# けしかメモリに格納されず、文字列を処理するときには、すべてこの表現を指して使います。これに
# よって文字列重複に伴うメモリ使用がなくなります。

x <- "This is a reasonably long string."
pryr::object_size(x)
## 136 B
y <- rep(x, 1000)
pryr::object_size(y)
## 8.13 kB
# 16.3.4 欠損値

NA # 論理
## [1] NA
NA_integer_ # 整数
## [1] NA
NA_real_ # 実数
## [1] NA
NA_character_ # 文字
## [1] NA
# 練習問題 p261

# 1. is.finite(x)と!is.infinite(x)の違いを述べなさい。

# To find out, try the functions on a numeric vector that includes a number and the five special values (NA, NaN, Inf, -Inf).

x <- c(0, NA, NaN, Inf, -Inf)
is.finite(x)
## [1]  TRUE FALSE FALSE FALSE FALSE
!is.infinite(x)
## [1]  TRUE  TRUE  TRUE FALSE FALSE
# is.finite considers only a number to be finite, and considers missing (NA),
# not a number (NaN), and positive and negative infinity to be not finite.
# However, since is.infinite only considers Inf and -Inf to be infinite,
# !is.infinite considers 0 as well as missing and not-a-number to be not infinite.
# So NA and NaN are neither finite or infinite. Mind blown.

# is.finite数値は有限であるとみなしNA、number(NaN)ではなくmissing()とみなし、正と負の無限大は有限ではないと考えます。しかし、is.infiniteのみを考慮Infし、-Inf無限大に、!is.infinite考えて0だけでなく、行方不明と非数は無限ではないように。
# だからNA、NaN有限でも無限でもない。心が吹かれました。


# 2. dplyr::near()のソースコードを読みなさい(ヒント:ソースコードを見るには括弧()を取る)。
# どのように動くか。

dplyr::near
## function (x, y, tol = .Machine$double.eps^0.5) 
## {
##     abs(x - y) < tol
## }
## <environment: namespace:dplyr>
# Instead of checking for exact equality, it checks that two numbers are within a certain tolerance, tol.
# By default the tolerance is set to the square root of .Machine$double.eps,
# which is the smallest floating point number that the computer can represent.
# 正確な等価性をチェックする代わりに、2つの数値が一定の許容値内にあるかどうかをチェックしtolます。
# デフォルトでは、公差は.Machine$double.eps、コンピュータが表現できる最小の浮動小数点数である平方根に設定されています。

# 3. 論理ベクトルには3つの値が可能だ。整数ベクトルはどれだけの値が可能か。実数ベクトルはど
# れだけの値が可能か。Googleを使って調べてみなさい。
.Machine
## $double.eps
## [1] 2.220446e-16
## 
## $double.neg.eps
## [1] 1.110223e-16
## 
## $double.xmin
## [1] 2.225074e-308
## 
## $double.xmax
## [1] 1.797693e+308
## 
## $double.base
## [1] 2
## 
## $double.digits
## [1] 53
## 
## $double.rounding
## [1] 5
## 
## $double.guard
## [1] 0
## 
## $double.ulp.digits
## [1] -52
## 
## $double.neg.ulp.digits
## [1] -53
## 
## $double.exponent
## [1] 11
## 
## $double.min.exp
## [1] -1022
## 
## $double.max.exp
## [1] 1024
## 
## $integer.max
## [1] 2147483647
## 
## $sizeof.long
## [1] 4
## 
## $sizeof.longlong
## [1] 8
## 
## $sizeof.longdouble
## [1] 16
## 
## $sizeof.pointer
## [1] 8
# The help for .Machine describes some of this:
# As all current implementations of R use 32-bit integers and uses IEC 60559 floating-point (double precision) arithmetic,
# The IEC 60559 or IEEE 754 format uses a 64 bit vector, but
# のための援助.Machineはこれのいくつかを記述する:
# Rの現在の実装はすべて32ビット整数を使用し、IEC 60559浮動小数点(倍精度)演算を使用するため、
# IEC 60559またはIEEE 754フォーマットは、64ビット・ベクトルを使用するが、
# 「Double-precision floating-point format - Wikipedia」 https://en.wikipedia.org/wiki/Double-precision_floating-point_format

# 4. 実数を整数に変換する少なくとも4つの関数についてブレインストーミングしなさい。どのよう
# な相違があるか。できるだけ厳密に述べなさい。

# truncating or rounding
# methods   0.5 -0.5    1.5 -1.5
# towards zero: 0   0   1   1
# away from zero    1   -1  2   -2
# largest towards  +∞)  1   0   2   -1
# smallest (towards−∞)  0   -1  1   -2
# even  0   0   2   -2
# odd   1   -1  1   -1
ceiling(-0.5)
## [1] 0
round(-0.5)
## [1] 0
floor(-0.5)
## [1] -1
trunc(-0.5)
## [1] 0
signif(-1.54, digits = 1)
## [1] -2
as.integer(-0.5)
## [1] 0
# See the Wikipedia article IEEE floating point for rounding rules.
# 「IEEE 754 - Wikipedia」 https://en.wikipedia.org/wiki/IEEE_754

# For rounding, R and many programming languages use the IEEE standard. This is “round to nearest, ties to even”. This is not the same as what you See the value of looking at the value of .Machine$double.rounding and its documentation.
x <- seq(-10, 10, by = 0.5)

round2 <- function(x, to_even = TRUE) {
  q <- x %/% 1
  r <- x %% 1
  q + (r >= 0.5)
}
x <- c(-12.5, -11.5, 11.5, 12.5)
round(x)
## [1] -12 -12  12  12
round2(x, to_even = FALSE)
## [1] -12 -11  12  13
#?round

x <- seq(-100.5, 100.5, by = 1)
#x
sum(x)
## [1] 0
sum(round(x))
## [1] 0
sum(round2(x))
## [1] 101
# 「Vancouver Stock Exchange - Wikipedia」 https://en.wikipedia.org/wiki/Vancouver_Stock_Exchange
# 「Disasters due to rounding error」 https://www.ma.utexas.edu/users/arbogast/misc/disasters.html


# 5. readrパッケージの関数でどれが文字列を、論理ベクトル、整数ベクトル、実数ベクトルに変換
# するか。

# parse_logical, parse_integer, and parse_number

# 16.4 アトミックベクトルを使う

# 16.4.1 型強制(Coercion)

# 明示的型強制は、as.logical(), as.integer(), as.double(), as.character()のような関数を呼び出したときに起こる。
# 暗黙型強制
# TRUEが1にFALSEが0に

x <- sample(20, 100, replace = TRUE)
y <- x > 10
sum(y) # 10より大きいのはいくつか?
## [1] 56
mean(y) # 10より大きいものの割合は?
## [1] 0.56
if (length(x)) {
  # 何かする
}
## NULL
if (length(x) > 0) {
  # 何かする
}
## NULL
typeof(c(TRUE, 1L))
## [1] "integer"
typeof(c(1L, 1.5))
## [1] "double"
typeof(c(1.5, "a"))
## [1] "character"
# 16.4.2 テスト関数
# is_logical(), is_integer(), is_double(), is_numeric(), is_character(), is_atomic(), is_list(), is_vector()
# is_scalar_atomic()のようなものも

# 16.4.3 スカラーとリサイクル規則
sample(10) + 100
##  [1] 106 102 105 107 110 103 104 101 109 108
runif(10) > 0.5
##  [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE
1:10 + 1:2
##  [1]  2  4  4  6  6  8  8 10 10 12
1:10 + 1:3
## Warning in 1:10 + 1:3: 長いオブジェクトの長さが短いオブジェクトの長さの倍数
## になっていません
##  [1]  2  4  6  5  7  9  8 10 12 11
# tidyverseではrep()で行う必要がある。

# tibble(x = 1:4, y = 1:2)
# Error: Column `y` must be length 1 or 4, not 2

tibble(x = 1:4, y = rep(1:2, 2))
## # A tibble: 4 x 2
##       x     y
##   <int> <int>
## 1     1     1
## 2     2     2
## 3     3     1
## 4     4     2
tibble(x = 1:4, y = rep(1:2, each = 2))
## # A tibble: 4 x 2
##       x     y
##   <int> <int>
## 1     1     1
## 2     2     1
## 3     3     2
## 4     4     2
# 16.4.4 ベクトルの名前付け
c(x = 1, y = 2, z = 4)
## x y z 
## 1 2 4
# purrr::set_names()で後から付けることもできます。
set_names(1:3, c("a", "b", "c"))
## a b c 
## 1 2 3
# 16.4.5 要素抽出
x <- c("one", "two", "three", "four", "five")
x[c(3, 2, 5)]
## [1] "three" "two"   "five"
x[c(1, 1, 5, 5, 5, 2)]
## [1] "one"  "one"  "five" "five" "five" "two"
# 負数の値は、指定位置の要素を削除する。
x[c(-1, -3, -5)]
## [1] "two"  "four"
# 正と負の値を混在させるとエラーになる。
# x[c(1, -1)]
# Error in x[c(1, -1)] : only 0's may be mixed with negative subscripts

x[0]
## character(0)
x <- c(10, 3, NA, 5, 8, 1, NA)
# xの欠損値以外すべて
x[!is.na(x)]
## [1] 10  3  5  8  1
# xの偶数値(または欠損値)全部
x[x %% 2 == 0]
## [1] 10 NA  8 NA
# 名前付きベクトルなら、文字ベクトルで部分集合を作ることができる。
x <- c(abc = 1, def = 2, xyz = 5)
x[c("xyz", "def")]
## xyz def 
##   5   2
x <- c("one", "two", "three", "four", "five")
x[]
## [1] "one"   "two"   "three" "four"  "five"
#x[1,]
# Error in x[1, ] : incorrect number of dimensions
#x[, -1]
# Error in x[, -1] : incorrect number of dimensions

# 部分集合の使い方についてもっと学習するには、『Advanced R』(http://bit.ly/subsetadvR )subsetadvR)の
# 「Subsetting」の章(邦題『R言語徹底解説』では「データ抽出」の章)を読むこと

# [[は単一要素しか抽出せず、名前は削除します。

# 練習問題 p267 (19.4 Using atomic vectors)
# 1. mean(is.na(x))はベクトルxについて何を教えるか。sum(!is.finite(x))ではどうか。
# 式mean(is.na(x))は、ベクトル内の欠損値の割合を計算します。
x <- c(1:10, NA, NaN, Inf, -Inf)
mean(is.na(x))
## [1] 0.1428571
# The expression mean(!is.finite(x)) calculates the proportion of values that are NA, NaN, or infinite.
mean(!is.finite(x))
## [1] 0.2857143
# 2. is.vector()についてのドキュメントを注意して読みなさい。実際には何のためのテストか。
# is.atomic()がアトミックベクトルについての定義と合致していないのはなぜか。

# この関数is.vectorは、オブジェクトに名前以外の属性がないかどうかだけをチェックします。したがって、listはベクトルです。
is.vector(list(a = 1, b = 2))
## [1] TRUE
# But any object that has an attribute (other than names) is not:
x <- 1:10
attr(x, "something") <- TRUE
is.vector(x)
## [1] FALSE
# The idea behind this is that object oriented classes will include attributes, including, but not limited to "class".
#The function is.atomic explicitly checks whether an object is one of the atomic types (“logical”, “integer”, “numeric”, “complex”, “character”, and “raw”) or NULL.
is.atomic(1:10)
## [1] TRUE
is.atomic(list(a = 1))
## [1] FALSE
# この関数is.atomicは、余分な属性を持っていてもオブジェクトをアトミックに見なします。
is.atomic(x)
## [1] TRUE
# 3. setNames()とpurrr::set_names()を比較対照しなさい。
setNames
## function (object = nm, nm) 
## {
##     names(object) <- nm
##     object
## }
## <bytecode: 0x000000000ef913e0>
## <environment: namespace:stats>
purrr::set_names
## function (x, nm = x, ...) 
## {
##     if (!is_vector(x)) {
##         abort("`x` must be a vector")
##     }
##     if (is_function(nm) || is_formula(nm)) {
##         nm <- as_function(nm)
##         nm <- nm(names2(x), ...)
##     }
##     else if (!is_null(nm)) {
##         nm <- as.character(nm)
##         nm <- chr(nm, ...)
##     }
##     if (!is_null(nm) && !is_character(nm, length(x))) {
##         abort("`nm` must be `NULL` or a character vector the same length as `x`")
##     }
##     names(x) <- nm
##     x
## }
## <environment: namespace:rlang>
# コードから、set_namesいくつかのサニティチェックが追加されています:xはベクトルでなければならず、オブジェクトと名前の長さが同じでなければなりません。

# 4. ベクトルを入力として、次を返す関数を作りなさい。
#   a. 末尾の値。[と[[とどちらを使うべきか。
last_value <- function(x) {
  # check for case with no length
  if (length(x)) {
    # Use [[ as suggested because it returns one element
    x[[length(x)]]  
  } else {
    x
  }
}
last_value(numeric())
## numeric(0)
last_value(1)
## [1] 1
last_value(1:10)
## [1] 10
#   b. 偶数番目の要素。
even_indices <- function(x) {
  if (length(x)) {
    x[seq_along(x) %% 2 == 0]
  } else {
    x
  }  
}
even_indices(numeric())
## numeric(0)
even_indices(1)
## numeric(0)
even_indices(1:10)
## [1]  2  4  6  8 10
# test using case to ensure that values not indices
# are being returned
even_indices(letters)
##  [1] "b" "d" "f" "h" "j" "l" "n" "p" "r" "t" "v" "x" "z"
#   c. 末尾以外の全要素。
not_last <- function(x) {
  if (length(x)) {
    x[-length(x)]
  } else {
    x
  }
}
not_last(1:5)
## [1] 1 2 3 4
x <- 1:5
x
## [1] 1 2 3 4 5
not_last(x)
## [1] 1 2 3 4
x
## [1] 1 2 3 4 5
#   d. 偶数だけ(しかも欠損値を含まない)。
even_numbers <- function(x) {
  x[!is.na(x) & (x %% 2 == 0)]
}
even_numbers(-10:10)
##  [1] -10  -8  -6  -4  -2   0   2   4   6   8  10
# 5. x[-which(x > 0)]がx[x <= 0]と同じでないのはなぜか。

# 欠損値は別々に扱われます。
x <- c(-5:5, Inf, -Inf, NaN, NA)
x[-which(x > 0)]
## [1]   -5   -4   -3   -2   -1    0 -Inf  NaN   NA
-which(x > 0)
## [1]  -7  -8  -9 -10 -11 -12
x[x <= 0]
## [1]   -5   -4   -3   -2   -1    0 -Inf   NA   NA
x <= 0
##  [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE
## [12] FALSE  TRUE    NA    NA
# 6. ベクトルの長さより大きい正数を与えて要素抽出すると何が起こるか。存在しない名前を与え
# て要素抽出すると何が起こるか。

# NA
(1:10)[11:12]
## [1] NA NA
# 16.5 再帰ベクトル(リスト)p267
x <- list(1, 2, 3)
x
## [[1]]
## [1] 1
## 
## [[2]]
## [1] 2
## 
## [[3]]
## [1] 3
str(x)
## List of 3
##  $ : num 1
##  $ : num 2
##  $ : num 3
x_named <- list(a = 1, b = 2, c = 3)
str(x_named)
## List of 3
##  $ a: num 1
##  $ b: num 2
##  $ c: num 3
y <- list("a", 1L, 1.5, TRUE)
str(y)
## List of 4
##  $ : chr "a"
##  $ : int 1
##  $ : num 1.5
##  $ : logi TRUE
z <- list(list(1, 2), list(3, 4))
str(z)
## List of 2
##  $ :List of 2
##   ..$ : num 1
##   ..$ : num 2
##  $ :List of 2
##   ..$ : num 3
##   ..$ : num 4
# 16.5.1 リストの可視化

x1 <- list(c(1, 2), c(3, 4))
x2 <- list(list(1, 2), list(3, 4))
x3 <- list(1, list(2, list(3)))


# 16.5.2 要素抽出
# リストの部分集合を作るには3つの方法があります。次のaという例を使って説明します。
a <- list(a = 1:3, b = "a string", c = pi, d = list(-1, -5))

# ● [はサブリストを抽出する。結果は常にリスト
str(a[1:2])
## List of 2
##  $ a: int [1:3] 1 2 3
##  $ b: chr "a string"
# ● [[はリストから単一成分を抽出する。リストでの階層が1つ下がる。
str(a[[1]])
##  int [1:3] 1 2 3
# ● $はリストの名前付き要素を抽出する略記法。[[と同様だが、引用符が必要ない。
a$a
## [1] 1 2 3
# 16.5.3 調味料のリスト


# 練習問題 p272 (Recursive Vectors (lists))
# 1. 入れ子になった集合として次のリストを書きなさい。
#   a. list(a, b, list(c, d), list(e, f))
#   b. list(list(list(list(list(list(a))))))
# 2. tibbleの要素抽出をリストの要素抽出であるかのように行うとどうなるか。リストとtibbleの
# 主な相違点は何か。

# tibbleサブセッティングは、リストと同じ方法で動作します。データフレームは列のリストと考えることができます。
# リストとaとの間の鍵tibbleは、すべての要素(列)が同じ長さでなければならないという制約があることです。
x <- tibble(a = 1:2, b = 3:4)
x[["a"]]
## [1] 1 2
x["a"]
## # A tibble: 2 x 1
##       a
##   <int>
## 1     1
## 2     2
x[1]
## # A tibble: 2 x 1
##       a
##   <int>
## 1     1
## 2     2
x[1, ]
## # A tibble: 1 x 2
##       a     b
##   <int> <int>
## 1     1     3
# 16.6 属性

x <- 1:10
attr(x, "greeting")
## NULL
attr(x, "greeting") <- "Hi!"
attr(x, "farewell") <- "Bye!"
attributes(x)
## $greeting
## [1] "Hi!"
## 
## $farewell
## [1] "Bye!"
# 1. Names are used to name the elements of a vector.
# 2. Dimensions (dims, for short) make a vector behave like a matrix or array.
# 3. Class is used to implement the S3 object oriented system.

# 『R言語徹底解説』の該当部分(7.2「S3」の節、 http://adv-r.had.co.nz/OO-essentials.html#s3

as.Date
## function (x, ...) 
## UseMethod("as.Date")
## <bytecode: 0x00000000156b6618>
## <environment: namespace:base>
methods("as.Date")
## [1] as.Date.character as.Date.date      as.Date.dates     as.Date.default  
## [5] as.Date.factor    as.Date.numeric   as.Date.POSIXct   as.Date.POSIXlt  
## see '?methods' for accessing help and source code
getS3method("as.Date", "default")
## function (x, ...) 
## {
##     if (inherits(x, "Date")) 
##         return(x)
##     if (is.logical(x) && all(is.na(x))) 
##         return(structure(as.numeric(x), class = "Date"))
##     stop(gettextf("do not know how to convert '%s' to class %s", 
##         deparse(substitute(x)), dQuote("Date")), domain = NA)
## }
## <bytecode: 0x0000000015873410>
## <environment: namespace:base>
getS3method("as.Date", "numeric")
## function (x, origin, ...) 
## {
##     if (missing(origin)) 
##         stop("'origin' must be supplied")
##     as.Date(origin, ...) + x
## }
## <bytecode: 0x0000000015875670>
## <environment: namespace:base>
# 16.7 強化ベクトル(Augmented vectors)

# 16.7.1 ファクタ

x <- factor(c("ab", "cd", "ab"), levels = c("ab", "cd", "ef"))
typeof(x)
## [1] "integer"
attributes(x)
## $levels
## [1] "ab" "cd" "ef"
## 
## $class
## [1] "factor"
# 16.7.2 日付と日付時刻
x <- as.Date("1971-01-01")
unclass(x)
## [1] 365
typeof(x)
## [1] "double"
attributes(x)
## $class
## [1] "Date"
x <- lubridate::ymd_hm("1970-01-01 01:00")
unclass(x)
## [1] 3600
## attr(,"tzone")
## [1] "UTC"
typeof(x)
## [1] "double"
attributes(x)
## $tzone
## [1] "UTC"
## 
## $class
## [1] "POSIXct" "POSIXt"
attr(x, "tzone") <- "US/Pacific"
x
## [1] "1969-12-31 17:00:00 PST"
attr(x, "tzone") <- "US/Eastern"
x
## [1] "1969-12-31 20:00:00 EST"
y <- as.POSIXlt(x)
typeof(y)
## [1] "list"
attributes(y)
## $names
##  [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"  
##  [8] "yday"   "isdst"  "zone"   "gmtoff"
## 
## $class
## [1] "POSIXlt" "POSIXt" 
## 
## $tzone
## [1] "US/Eastern" "EST"        "EDT"
# 16.7.3 tibble p276

tb <- tibble::tibble(x = 1:5, y = 5:1)
typeof(tb)
## [1] "list"
attributes(tb)
## $names
## [1] "x" "y"
## 
## $class
## [1] "tbl_df"     "tbl"        "data.frame"
## 
## $row.names
## [1] 1 2 3 4 5
df <- data.frame(x = 1:5, y = 5:1)
typeof(df)
## [1] "list"
attributes(df)
## $names
## [1] "x" "y"
## 
## $row.names
## [1] 1 2 3 4 5
## 
## $class
## [1] "data.frame"
# 練習問題 p276 (Augmented Vectors)

# 1. hms::hms(3600)は何を返すか。表示するとどうなるか。どの基本型で構築された強化ベクトル
# か。どんな属性を使うか。
x <- hms::hms(3600)
class(x)
## [1] "hms"      "difftime"
x
## 01:00:00
typeof(x)
## [1] "double"
attributes(x)
## $units
## [1] "secs"
## 
## $class
## [1] "hms"      "difftime"
# 2. 異なる長さの列を持つtibbleを作ってみよう。何が起こるか。
tibble(x = 1, y = 1:5)
## # A tibble: 5 x 2
##       x     y
##   <dbl> <int>
## 1     1     1
## 2     1     2
## 3     1     3
## 4     1     4
## 5     1     5
#tibble(x = 1:3, y = 1:4)
# Error: Column `x` must be length 1 or 4, not 3

# 3. これまでの定義に基づくなら、tibbleの列をリストにすることは可能か。
# 可能
tibble(x = 1:3, y = list("a", 1, list(1:3)))
## # A tibble: 3 x 2
##       x          y
##   <int>     <list>
## 1     1  <chr [1]>
## 2     2  <dbl [1]>
## 3     3 <list [1]>