# -*- coding: utf-8 -*-
# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .r
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: R
#     name: ir
# ---

# + [markdown] colab_type="text" id="view-in-github"
# <a href="https://colab.research.google.com/github/anicelysantos/tutorial_r/blob/main/pacotes_carga_dados.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="re-0qzuXW7yx"
library(readr) 


# + [markdown] id="5GLIG-f__Pj4"
# # Arquivos .csv e .txt

# + colab={"base_uri": "https://localhost:8080/", "height": 497} id="MRjaJYWmbIkK" outputId="87a8d223-32a7-4a55-c3df-426b2a18eacd"
#arquivos separados por vírgula
imdb_csv <- read.csv(file = '/content/sample_data/imdb.csv')
head(imdb_csv)

# + colab={"base_uri": "https://localhost:8080/", "height": 497} id="-jgupAHK9sA1" outputId="ca8ee839-ab3f-4208-bd5e-796e809323fe"
#arquivos separados por ponto e virgula
imdb_csv2 <- read.csv2('/content/sample_data/imdb2.csv')
head(imdb_csv2)

# + colab={"base_uri": "https://localhost:8080/", "height": 688} id="SDRSmXkq-Wrb" outputId="8fe049fa-0302-4b0b-a761-e2c398610cf5"
#Arquivos txt, o \t é a tabulação
imdb_txt <- read_delim('/content/sample_data/imdb.txt')
head(imdb_txt)

# + [markdown] id="OZ-YcZdB_KwX"
# # Locale

# + colab={"base_uri": "https://localhost:8080/", "height": 226} id="V-SsKqQs_BEF" outputId="1108caef-8691-428c-ace6-626aaf42510f"
locale()

# + colab={"base_uri": "https://localhost:8080/", "height": 226} id="mPvSHCUn_bmi" outputId="6b92bc9f-dedd-4032-d4fa-64d745b1669c"
locale(date_names = 'pt')

# + colab={"base_uri": "https://localhost:8080/", "height": 226} id="N2RdfDeS_jIR" outputId="44dcc79d-88eb-4809-cee2-946a815c225b"
locale(decimal_mark = ',')

# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="eq1YaT5n_qiq" outputId="48dc661c-a7b9-41ae-e19d-267e4f7796d1"
frase_com_acentos <- 'você comerá uma maçã amanhã à tarde'
Encoding(frase_com_acentos)

# + id="B8hBqPeL__6b"
Encoding(frase_com_acentos) <- 'latin1'

# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="PB685eoqAICJ" outputId="76a5c553-3e6f-4634-be0d-34fac1b23d58"
frase_com_acentos

# + colab={"base_uri": "https://localhost:8080/", "height": 688} id="WjurZd9AAP_q" outputId="cabf7085-53b3-4b08-e7c7-61255639bc05"
outro_encoding <- read_csv('/content/sample_data/imdb.csv', locale = locale(encoding = 'latin1'))
head(outro_encoding)

# + [markdown] id="mw7Zc6opA0o7"
# # Parseando valores

# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="m2PrW6NIAiyy" outputId="c73044eb-8ab5-4635-8458-8ff3c7a16a91"
parse_number(c('5','5.0','5,0','R$5.00','5a'))

# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="smkFN9ItBMQe" outputId="7dce3caf-fd92-4561-f7f0-b2ffccfc03a3"
parse_number('5,0', locale = locale(decimal_mark = ','))

# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="caH9nlwTBc0a" outputId="988e2fd5-21e9-4278-824d-0c54732fb1cf"
#Inglês
parse_date(
  '01/june/2010',
  format = '%d/%B/%Y'
)

# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="wWY8qsVrBvya" outputId="633cf00f-d174-4f03-fbc2-e7aa2fd598b5"
#Português
parse_date(
  '01/junho/2021',
  format = '%d/%B/%Y',
  locale = locale(date_names = 'pt')
)

# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="RzT59YvMCByy" outputId="28cc4cd3-6213-4e6e-cb45-625c6309f94f"
#Pode especificar NAs
parse_number(c('5', '5.0', '5,0', 'R$5.00', '5 a'), na = '5 a')

# + [markdown] id="Ahpp57U_CoAo"
# Outras funções úteis:
# * `readr::parse_integer()`, para parsear números inteiros
# * `readr::parse_character()`, para parsear strings
# * `readr::parse_date()`, `readr::parse_time()`, `readr::parse_datetime()` para parsear datas, horas e data/horas.

# + [markdown] id="qrDejRt9DP-o"
# # Salvando arquivos de texto

# + id="kswVJO0-ClBM"
#arquivo .csv
write_csv(x = mtcars, file='/content/sample_data/mtcars.csv')

# + id="esWrFaNqDmVp"
#Base separada por tabulação
write_delim(x = mtcars, file='/content/sample_data/mtcars.txt', delim='\t')

# + [markdown] id="HOlUVzkMD5hS"
# # Arquivos .rds

# + id="c0rtTLUgD3QE"
#Esses arquivos só podem ser lidos dentro do R
write_rds(mtcars, file='mtcars.rds', compress='gz')

# + colab={"base_uri": "https://localhost:8080/", "height": 375} id="wvRXRV8gEO2q" outputId="0e214655-9f29-401b-847a-729b50fce5c2"
imdb_rds <- read_rds(file='mtcars.rds')
head(imdb_rds)

# + [markdown] id="WiEBOhkHEjWc"
# # Exercicios

# + [markdown] id="b_rPJxmjEsmU"
# 1. Qual a diferença entre as funções `read_csv()` e `read_csv2()`? 
#
# A primeira lê arquivos separados por vígula e a segunda separados por ponto e vírgula

# + [markdown] id="u7G8eg2sE7_h"
# 2. Leia o arquivo imdb.csv utilizando a função read_delim().

# + colab={"base_uri": "https://localhost:8080/", "height": 688} id="tLfdyDuxEq_Q" outputId="41f8df6e-80ca-435c-a868-5d78991fd6df"
leia <- read_delim('/content/sample_data/imdb.csv', delim = ',')
head(leia)

# + [markdown] id="59uv7tw1FPeg"
# 3. Escreva a base `mtcars` em um arquivo `mtcars.csv` que não contenha o nome das colunas.

# + id="PuwyqumHEbRL"
write_csv(mtcars,'sc_mtcars.csv', col_names=FALSE)

# + [markdown] id="QnSOJY4iF-85"
# 4. Use a função `write_rds()` para salvar em arquivos:
#
# a) um número

# + id="sh3jXyKIFqW0"
numero <- 5

write_rds(numero,'numero.rds')

# + [markdown] id="yylacixYG24I"
# b) um vetor de strings

# + id="8PWEOy84G2Gj"
estados <- c('PE', 'CE', 'PB','RN')
write_rds(estados, 'estados.rds')

# + [markdown] id="h3sUCgbOHMqY"
# Uma lista com valores numéricos, textuais e lógicos

# + id="cUSVpAVcHHmg"
lista <- list(numero = 1, texto = c('M', 'F', 'F'), logico = FALSE)
write_rds(lista,'lista.rds')

# + [markdown] id="aDQzOfx8HiVk"
# d) As 3 primeiras colunas da base `mtcars`
#

# + id="Iuxg7TDCHgSc"
write_rds(mtcars[,1:3], 'mtcars_3_colunas.rds')

# + [markdown] id="dfxbOe5THyV1"
# 5. Utilize a função `read_rds()` para importar de volta para o R os arquivos criados no exercício 4.

# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="8Q1iR8oQHwz0" outputId="8e5fd848-04f4-4900-dfcb-d2511dbdb93c"
read_rds('numero.rds')

# + colab={"base_uri": "https://localhost:8080/", "height": 34} id="ZEHd9KfAH69z" outputId="66ebbcaa-abaf-4a73-87df-b596c6ab985e"
read_rds('estados.rds')

# + colab={"base_uri": "https://localhost:8080/", "height": 149} id="O2ncibiXH9Zl" outputId="ec2ee8a1-d3ed-494b-aa83-17d4c74b94ab"
read_rds('lista.rds')

# + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="Tp_gSxXTIEm1" outputId="0c316782-1ea2-4d69-9823-1612735d0499"
read_rds('mtcars_3_colunas.rds')

StarcoderdataJupyterScriptsDedupFiltered