-
Notifications
You must be signed in to change notification settings - Fork 0
/
04-dates-categorical-variables.Rmd
638 lines (463 loc) · 20.7 KB
/
04-dates-categorical-variables.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# Fatores e datas
Script da aula do Módulo IV abaixo.
```{r, echo=FALSE}
xfun::embed_file('Scripts/04-dates-categorical-variables.R')
```
## O pacote forcats {#forcats}
```{r, include=FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
out.width="75%",
fig.align = "center"
)
```
Em R, os *factors* são uma classe de dados que permitem categorias ordenadas
com um conjunto fixo de valores aceitáveis.
Normalmente, você converteria uma coluna de caractere ou classe numérica em um
fator se quiser definir uma ordem intrínseca para os valores (“níveis”) para
que eles possam ser exibidos de forma não alfabética em gráficos e tabelas.
Outro uso comum de fatores é padronizar as legendas dos gráficos para que não
flutuem se certos valores estiverem temporariamente ausentes dos dados.
Vamos demonstrar o uso de funções do pacote `forcats` (um nome abreviado
para “**For cat***egorical variables*”) e algumas funções básicas do R.
Isso significa que fatores são úteis. Eles representam uma forma muito prática
de lidar com variáveis categorizadas, tanto para fins de modelagem quanto
para fins de visualização.
As principais funções do `forcats` servem para alterar a **ordem** e modificar
os **níveis** de um fator. Para exemplificar a utilidade dessas funções,
vamos utilizá-las em situações do dia a dia.
Se você não tem o pacote `{forcats}` ou `{tidyverse}`, instalado rode o código abaixo
antes de utilizá-lo:
```{r, eval = FALSE}
install.packages("forcats")
```
Nos exemplos a seguir, utilizarmos os seguintes pacotes:
```{r message=FALSE}
library(forcats)
library(ggplot2)
library(dplyr)
```
### O que são fatores?
Fatores são uma classe de objetos no R criada para representar as variáveis
categóricas numericamente.
Eles são necessários pois muitas vezes precisamos representar variáveis
categóricas como números. Quando estamos fazendo um gráfico, por exemplo, só
podemos mapear variáveis numéricas em seus eixos, pois o plano cartesiano é
formado por duas retas de números reais.
O que fazemos então quando plotamos uma variável categórica?
Nós a transformamos em fatores.
Mas como a manipulação de fatores é diferente da manipulação de números e
strings (graças aos famosos *levels*), tarefas que parecem simples, como
ordenar as barras de um gráfico de barras, acabam se tornando grandes
desafios quando não sabemos lidar com essa classe.
Nos exemplos a seguir, vamos utilizar a base `starwars` (do pacote `{dplyr}`) para aprendermos a fazer as principais operações com fatores utilizando o pacote `{forcats}`.
### Modificando níveis de um fator
Vamos trabalhar primeiro com a coluna `sex`, que diz qual é o sexo de cada personagem. As possibilidades são:
```{r}
starwars %>%
pull(sex) %>%
unique()
```
Veja que se transformarmos a coluna em fator, esses serão os *levels* da variável, não importa se o sub-conjunto que estivermos observando possua ou não todas as categorias.
```{r}
starwars %>%
mutate(sex = as.factor(sex)) %>%
pull(sex) %>%
head()
```
Vamos criar um objeto com os 16 primeiros valores da coluna `sex` já transformados em fator.
```{r}
fator_sex <- starwars %>%
pull(sex) %>%
as.factor() %>%
head(16)
fator_sex
```
Para mudar os níveis de um fator, podemos utilizar a função `lvls_revalue()`. Veja que, ao mudarmos os níveis de um fator, o *label* de cada valor também muda. Os novos valores precisam ser passados conforme a ordem dos níveis antigos.
```{r}
lvls_revalue(
fator_sex,
new_levels = c("Fêmea", "Hermafrodita", "Macho", "Nenhum")
)
```
Essa função é uma boa alternativa para mudar o nome das categorias de uma variável antes de construir um gráfico.
```{r}
starwars %>%
filter(!is.na(sex)) %>%
count(sex) %>%
mutate(
sex = lvls_revalue(sex, c("Fêmea", "Hermafrodita", "Macho", "Nenhum"))
) %>%
ggplot() +
geom_col(aes(x = sex, y = n))
```
Como as colunas no gráfico respeitam a ordem dos níveis do fator, não importa a ordem que as linhas aparecem na tabela, o gráfico sempre será gerado com as colunas na mesma ordem. Assim, se quiséssemos alterar a ordem das barras do gráfico anterior, precisamos mudar a ordem dos níveis do fator `sex`.
### Mudando a ordem dos níveis de um fator
Para mudar a ordem dos níveis de um fator, podemos utilizar a função `lvls_reorder()`. Basta passarmos qual a nova ordem dos fatores, com relação à ordem anterior. No exemplo abaixo definimos que, na nova ordem,
- a primeira posição terá o nível que estava na terceira posição na ordem antiga;
- a segunda posição terá o nível que estava na primeira posição na ordem antiga;
- a terceira posição terá o nível que estava na quarta posição na ordem antiga;
- a quarta posição terá o nível que estava na segunda posição na ordem antiga.
```{r}
lvls_reorder(fator_sex, c(3, 1, 4, 2))
```
Assim, poderíamos usar essa nova ordem para ordenar as colunas do nosso gráfico.
```{r}
starwars %>%
filter(!is.na(sex)) %>%
count(sex) %>%
mutate(
sex = lvls_revalue(sex, c("Fêmea", "Hermafrodita", "Macho", "Nenhum")),
sex = lvls_reorder(sex, c(3, 1, 4, 2))
) %>%
ggplot() +
geom_col(aes(x = sex, y = n))
```
Repare que precisamos passar a nova ordem na mão, o que pode deixar de funcionar se a nossa base mudar (recebemos mais linhas ou fizermos um filtro anteriormente).
Anterior ao `mutate()` temos a seguinte tabela:
```{r}
starwars %>%
filter(!is.na(sex)) %>%
count(sex)
```
O que queremos é que os níveis da coluna `sex` sejam ordenados segundo os valores da coluna `n`, isto é, quem tiver o maior valor de `n` deve ser o primeiro nível, o segundo maior valor de `n` seja o segundo nível e assim por diante.
Podemos melhorar esse código utilizando a função `fct_reorder()`. Com ela, em vez de definirmos na mão a ordem dos níveis do fator, podemos ordená-lo segundo valores de uma segunda variável.
```{r}
starwars %>%
filter(!is.na(sex)) %>%
count(sex) %>%
mutate(
sex = lvls_revalue(sex, c("Fêmea", "Hermafrodita", "Macho", "Nenhum")),
sex = fct_reorder(sex, n)
) %>%
ggplot() +
geom_col(aes(x = sex, y = n))
```
É quase o que queríamos! O problema é que os níveis estão sendo ordenados de forma crescente e gostaríamos de ordenar na ordem decrescente. Para isso, basta utilizarmos o parâmetro `.desc`.
```{r}
starwars %>%
filter(!is.na(sex)) %>%
count(sex) %>%
mutate(
sex = lvls_revalue(sex, c("Fêmea", "Hermafrodita", "Macho", "Nenhum")),
sex = fct_reorder(sex, n, .desc = TRUE)
) %>%
ggplot() +
geom_col(aes(x = sex, y = n))
```
Agora sim! Com esse código, as colunas estarão sendo ordenadas pela frequência, independentemente dos valores de `n` e `sex` que chegarem no `mutate()`.
Se olharmos a documentação da função `fct_reorder()` vamos descobrir que esse exemplo é apenas um caso particular de como podemos utilizá-la. No contexto geral, ela ordena os níveis de um fator segundo **uma função** dos valores de uma segunda variável.
Se em vez de construirmos um gráfico de barras da frequência da variável `sex`, construíssemos boxplots da altura para cada sexo diferente, teríamos o gráfico a seguir.
```{r}
starwars %>%
filter(!is.na(sex)) %>%
ggplot() +
geom_boxplot(aes(x = sex, y = height))
```
Se quiséssemos ordenar cada boxplot (pela mediana, por exemplo), continuamos podendo usar a função `fct_reorder()`. Veja que ela possui o argumento `.fun`, que indica qual função será utilizada na variável secundária para determinar a ordem dos níveis.
No exemplo abaixo, utilizamos `.fun = median`, o que significa que, para cada nível da variável `sex`, vamos calcular a mediana da variável `height` e ordenaremos os níveis de `sex` conforme a ordem dessas medianas. Assim, o primeiro nível será o sexo com menor altura mediana, o segundo nível será o sexo com a segunda menor algura media e assim por diante. Se quiséssemos ordenar de forma decrescente, bastaria utilizar o argumento `.desc = TRUE`.
```{r}
starwars %>%
filter(!is.na(sex)) %>%
mutate(
sex = lvls_revalue(sex, c("Fêmea", "Hermafrodita", "Macho", "Nenhum")),
sex = fct_reorder(sex, height, .fun = median, na.rm = TRUE)
) %>%
ggplot() +
geom_boxplot(aes(x = sex, y = height))
```
Também poderíamos ordenar pelo máximo, utilizando `.fun = max`. Neste argumento, podemos usar qualquer função sumarizadora: `min()`, `mean()`, `median()`, `max()`, `sd()`, `var()` etc.
```{r}
starwars %>%
filter(!is.na(sex)) %>%
mutate(
sex = lvls_revalue(sex, c("Fêmea", "Hermafrodita", "Macho", "Nenhum")),
sex = fct_reorder(sex, height, .fun = max, na.rm = TRUE)
) %>%
ggplot() +
geom_boxplot(aes(x = sex, y = height))
```
### Colapsando níveis de um fator
Imagine que quermos fazer um gráfico de barras com a frequência de personagens por espécie.
```{r}
starwars %>%
ggplot(aes(x = species)) +
geom_bar()
```
O gráfico resultante é horrível, pois temos muitas espécies diferentes. Uma solução seria agrupar as espécies menos frequentes, criando uma nova categoria (*outras*, por exemplo).
Para isso, podemos usar a função `fct_lump()`. Vamos fazer isso primeiro com o vetor de espécies.
```{r}
fator_especies <- as.factor(starwars$species)
fator_especies
```
Temos 37 espécies diferentes na base. Podemos deixar apenas as 3 mais frequentes da seguinte forma:
```{r}
fct_lump(fator_especies, n = 3)
```
O fator resultante possui 4 níveis: `Droid`, `Gungan`, `Human` e `Other`. Os 3 primeiros níveis são os mais frequentes, enquanto o nível `Other` foi atribuído a todos os outros 34 níveis que existiam anteiormente.
Poderíamos definir o nome do nível `Others` usando o argumento `other_level`.
```{r}
fct_lump(fator_especies, n = 3, other_level = "Outras espécies")
```
Também podemos transformar em `Outras` os níveis cuja frequência relativa é menor que um determinado limite, por exemplo, 2%. No exemplo abaixo, apenas espécies que representam mais de 2% dos personagem na base são mantidas. As demais foram transformadas em `Outras`.
```{r}
fct_lump(fator_especies, p = 0.02, other_level = "Outras")
```
Com isso, já conseguimos fazer um gráfico de barras mais agradável.
```{r}
starwars %>%
filter(!is.na(species)) %>%
mutate(species = fct_lump(species, n = 2)) %>%
ggplot(aes(x = species)) +
geom_bar()
starwars %>%
filter(!is.na(species)) %>%
mutate(
species = fct_lump(species, p = 0.02),
species = fct_infreq(species) # Ordena pela frequência de cada nível
) %>%
ggplot(aes(x = species)) +
geom_bar()
```
Também é possível colapsar níveis criando manualmente os grupos. Para isso, utilizamos a função `fct_collapse()`. No exemplo a seguir, reclassificamos os níveis da variável `eye_color`. Os níveis não listados são reclassificados como `"outros"`.
```{r}
fator_cor_olhos <- as.factor(starwars$eye_color)
fct_collapse(
fator_cor_olhos,
preto = "black",
castanho = c("brown", "hazel"),
azul_verde = c("blue", "green"),
exotico = c("pink", "red", "white"),
colorido = c("red, blue", "green, yellow"),
other_level = "outros"
)
```
### Outras funções úteis
A seguir, listamos outras funções úteis do pacote `{forcats}`, apresentando exemplos simples de como usá-las.
```{r}
fator <- factor(c("a", "b", "a", "c", "c", "a"))
fator
```
#### `fct_c()` {-}
Junta dois fatores (e seus níveis).
```{r}
fator2 <- factor(c("d", "e"))
fct_c(fator, fator2)
```
#### `fct_count()` {-}
Devolve a frequência dos níveis de um vetor.
```{r}
fct_count(fator)
```
#### `fct_expand()` {-}
Acrescenta níveis a um fator
```{r}
fct_expand(fator, c("d", "e"))
```
#### `fct_rev()` {-}
Inverte os níveis de um fator.
```{r}
fct_rev(fator)
```
### Exercícios
A base `casas` nos exercícios abaixo está no pacote `dados`:
```{r, eval = FALSE}
remotes::install_github("cienciadedatos/dados")
```
**1.** Qual a diferença nos fatores criados com os códigos abaixo?
```{r, eval = FALSE}
fator1 <- as.factor(c("c", "a", "z", "B"))
fator2 <- forcats::as_factor(c("c", "a", "z", "B"))
```
**2.** Ordene os níveis do fator `frutas` conforme a sua preferência, isto é, as que você mais gosta primeiro e as que você menos gosta por último.
```{r, eval = FALSE}
frutas <- as.factor(c("maçã", "banana", "mamão", "laranja", "melancia"))
```
**3.** Com base no vetor `series`, resolva os itens a seguir.
```{r, eval = FALSE}
series <- as.factor(c("Game of Thrones", "How I Met your Mother", "Friends", "Lost", "The Office", "Breaking Bad"))
```
- **a.** Ordene os níveis do vetor `series` conforme a sua preferência, isto é, as que você mais gosta primeiro e as que você menos gosta por último.
- **b.** Junte ao vetor `series` o vetor `novas_series` a seguir, reordenando os níveis para manter a sua ordem de preferência.
```{r, eval = FALSE}
novas_series <- as.factor(c("The Boys", "Stranger Things", "Queen's Gambit"))
```
- **c.** Renomeie o níveis do vetor criado no item (b) para os nomes em Português das séries. Mantenha o mesmo nome caso não haja tradução.
**4.** Ordene as categorias do eixo y do gráfico abaixo para que os pontos no eixo x fique em ordem crescente.
```{r}
library(dplyr)
library(ggplot2)
mtcars %>%
tibble::rownames_to_column("modelo") %>%
ggplot(aes(x = mpg, y = modelo)) +
geom_point()
```
**5.** Utilize a base `dados::casas` para fazer um gráfico de barras mostrando as vizinhanças (coluna `vizinhanca`) com casas mais caras (segundo a coluna `venda_valor`). O gráfico deve conter as 9 vizinhanças mais frequentes e as demais devem ser agrupadas em uma categoria chamada `Outras vizinhanças`.
```{r, include=FALSE}
knitr::opts_chunk$set(
fig.align = "center",
cache = TRUE,
collapse = TRUE
)
```
## O pacote lubridate
Trabalhar com datas no R era uma chateação. As funções do R base são, em grande parte, contraintuitivas e podem mudar de acordo com o tipo do objeto que você está usando (data, hora, data/hora). Além disso, características como fusos horários, anos bissextos, horários de verão, entre outras, podem não estar bem especificadas ou nem mesmo sendo levadas em conta.
O pacote `{lubridate}`, criado por [Garrett Grolemund](https://github.com/garrettgman) e [Hadley Wickham](https://github.com/hadley), surgiu para lidar com esses problemas, fazendo o trabalho com datas ser muito mais fácil.
Antes de começar a usar, você precisa instalar e carregar o pacote.
```{r, eval = FALSE}
install.packages("lubridate")
library(lubridate)
```
```{r, include=FALSE}
library(lubridate)
library(magrittr)
library(tibble)
library(dplyr)
# https://github.com/tidyverse/lubridate/issues/928
if (grepl("darwin", R.version$os))
Sys.setenv("TZDIR" = "/Library/Frameworks/R.framework/Resources/share/zoneinfo/")
```
Neste seção, falaremos sobre:
- transformar e extrair datas;
- algumas funções úteis para trabalhar com datas;
- trabalhar com fusos horários; e
- operações aritméticas com datas.
### A classe `date`
Datas no R são tratadas como um tipo especial de objeto, com classe `date`. Há várias formas de criar objetos dessa classe com o pacote `{lubridate}`:
```{r}
data_string <- "21-10-2015"
class(data_string)
# data_date <- date(data_string)
# class(data_date)
data_date
data_as_date <- as_date(data_string)
class(data_as_date)
data_as_date
data_mdy <- dmy(data_string)
class(data_mdy)
data_mdy
```
Veja que as funções `date()` e `as_date()` converteram a *string* para data, mas não devolveram o valor esperado. A função `dmy()` resolve esse problema estabelecendo explicitamente a ordem dia-mês-ano. Existem funções para todas as ordens possíveis: `dmy()`, `mdy()`, `myd()`, `ymd()`, `ydm()` etc.
As funções `date()` e `as_date()` assumem que a ordem segue o padrão da língua inglesa: ano-mês-dia (ymd).
```{r}
# date("2015-10-21")
as_date("2015-10-21")
```
Uma grande facilidade que essas funções trazem é poder criar objetos com classe `date` a partir de números e *strings* em diversos formatos.
```{r}
dmy(21102015)
dmy("21102015")
dmy("21/10/2015")
dmy("21.10.2015")
```
Se além da data você precisar especificar o horário, basta usar as funções do tipo `ymd_h()`, `ymd_hm()`, `ymd_hms()`, sendo que também há uma função para cada formato de dia-mês-ano.
```{r}
ymd_hms(20151021165411)
```
No R base, utilizamos a função `as.Date()` para transformar uma string em data:
```{r}
data_base <- as.Date("2015-10-21")
class(data_base)
data_base
```
Repare que a função `date()` do R base retorna a data e horário no momento da execução:
```{r}
base::date()
```
### Funções úteis
O `lubridate` traz diversas funções para extrair os componentes de um objeto da classe `date`.
- `second()` - extrai os segundos.
- `minute()` - extrai os minutos.
- `hour()` - extrai a hora.
- `wday()` - extrai o dia da semana.
- `mday()` - extrai o dia do mês.
- `month()` - extrai o mês.
- `year()` - extrai o ano.
Os nomes são tão óbvios que a explicação do que cada função faz é praticamente desnecessária.
```{r}
bday <- ymd_hms("1989-07-29 030142")
bday
second(bday)
day(bday)
month(bday)
year(bday)
wday(bday)
wday(bday, label = TRUE)
```
Você também pode usar essas funções para atribuir esses componentes a uma data:
```{r}
data <- dmy("01/04/1991")
data
hour(data) <- 20
data
```
Também existem funções para extrair a data no instante da execução.
```{r}
# Data e horário do dia em que essa página foi editada pela última vez.
today()
now()
```
### Fusos horários
Uma característica inerente das datas é o fuso horário. Se você estiver trabalhando com datas de eventos no Brasil e na Escócia, por exemplo, é preciso verificar se os valores seguem o mesmo fuso horário. Além disso, quando a data exata de um evento for relevante, você pode precisar converter horários para outros fusos para comunicar seus resultados em outros países.
Para fazer essas coisas, o `lubridate` fornece as funções `with_tz()` e `force_tz()`. Veja um exemplo de como usá-las.
```{r}
estreia_GoT <- ymd_hms("2017-07-16 22:00:00", tz = "America/Sao_Paulo")
estreia_GoT
# Devolve qual seria a data em outro fuso
with_tz(estreia_GoT, tzone = "GMT")
with_tz(estreia_GoT, tzone = "US/Alaska")
# Altera o fuso sem mudar a hora
force_tz(estreia_GoT, tzone = "GMT")
```
### Operações com datas
O pacote `lubridate` possui ainda funções para calcular intervalos e fazer operações aritméticas com datas.
#### Intervalos {-}
Intervalos podem ser salvos em objetos com classe `interval`.
```{r}
inicio <- dmy("01-04-1991")
evento <- dmy("31-10-1993")
sobrev <- interval(inicio, evento)
sobrev
class(sobrev)
```
Você pode verificar se dois intervalos tem intersecção com a função `int_overlaps()`.
```{r}
# Outra forma de definir um intervalo: o operador %--%
intervalo_1 <- dmy("01-02-2003") %--% dmy("02-03-2005")
intervalo_2 <- dmy("04-05-2004") %--% dmy("12-03-2012")
int_overlaps(intervalo_1, intervalo_2)
```
#### Aritmética com datas
Veja alguns exemplos de operações aritméticas que você pode fazer utilizando funções do `lubridate`:
```{r}
# Somando datas
data <- dmy("31/01/2000")
data + ddays(1)
data + dyears(1)
# A operação abaixo retornaria uma data inválida
# por isso obtemos NA
data + months(1)
# Criando datas recorrentes
reuniao <- dmy("18-03-2017")
reunioes <- reuniao + weeks(0:10)
reunioes
# Duração de um intervalo
intervalo <-dmy("01-03-2003") %--% dmy("31-03-2003")
intervalo / ddays(1) # Número de dias
intervalo / dminutes(1) # Número de minutos
as.period(intervalo)
```
Para mais informações sobre o`lubridate`, visite o [vignette do pacote](https://cran.r-project.org/web/packages/lubridate/vignettes/lubridate.html).
### Exercícios
Nos exercícios a seguir, vamos utilizar a base `lakers`, que contém estatísticas jogo a jogo do [Los Angeles Lakers](http://www.nba.com/lakers/) na temporada 2008-2009.
```{r}
lakers %>% as_tibble()
```
**1.** Repare que a coluna `date` no data.frame é um vetor de inteiros. Transforme essa coluna em um vetor de valores com classe `date`.
**2.** Crie uma coluna que junte as informações de data e tempo de jogo (colunas `date` e `time`) em objetos da classe `date`.
**3.** Crie as colunas `dia`, `mês` e `ano` com as respectivas informações sobre a data do jogo.
**4.** Em média, quanto tempo o Lakers demora para arremessar a primeira bola no primeiro período?
**Dica**: arremessos são representados pela categoria `shot` da coluna `etype`.
**5.** Em média, quanto tempo demora para sair a primeira cesta de três pontos? Considere toda a base, e cestas de ambos os times.
**6.** Construa boxplots do tempo entre pontos consecultivos para cada períodos. Considere toda a base de dados e apenas pontos do Lakers.
**7.** Qual foi o dia e mês do jogo que o Lakers demorou mais tempo para fazer uma cesta? Quanto tempo foi?