0% found this document useful (0 votes)
1 views6 pages

Criando Data Frame

This document provides a lesson on creating and using data frames in R, highlighting their importance in data analysis. It covers steps for loading necessary packages, generating data frames from vectors, and inspecting them using functions like `head()`, `str()`, and `glimpse()`. The activity encourages users to practice by creating their own data frames and offers solutions for verification.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views6 pages

Criando Data Frame

This document provides a lesson on creating and using data frames in R, highlighting their importance in data analysis. It covers steps for loading necessary packages, generating data frames from vectors, and inspecting them using functions like `head()`, `str()`, and `glimpse()`. The activity encourages users to practice by creating their own data frames and offers solutions for verification.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

title: "Lesson 2: Create your own data frame"

output: html_document
---

## Background for this activity


This activity is focused on creating and using data frames in `R`. A
data frame is a collection of columns containing data, similar to a
spreadsheet or SQL table. Data frames are one of the basic tools you
will use to work with data in `R`. And you can create data frames from
different data sources.

There are three common sources for data:

- A`package` with data that can be accessed by loading that `package`


- An external file like a spreadsheet or CSV that can be imported into
`R`
- Data that has been generated from scratch using `R` code

Wherever data comes from, you will almost always want to store it in a
data frame object to work with it. Now, you can start creating and
exploring data frames with the code chunks in the RMD space. To
interact with the code chunk, click the green arrow in the top-right
corner of the chunk. The executed code will appear in the RMD space
and your console.

Throughout this activity, you will also have the opportunity to


practice writing your own code by making changes to the code chunks
yourself. If you encounter an error or get stuck, you can always check
the Lesson2_Dataframe_Solutions .rmd file in the Solutions folder
under Week 3 for the complete, correct code.

## Step 1: Load packages

Start by installing the required package; in this case, you will want
to install `tidyverse`. If you have already installed and loaded
`tidyverse` in this session, feel free to skip the code chunks in this
step.

```{r}
install.packages("tidyverse")
```

Once a package is installed, you can load it by running the


`library()` function with the package name inside the parentheses:

```{r}
library(tidyverse)
```

## Step 2: Create data frame

Sometimes you will need to generate a data frame directly in `R`.


There are a number of ways to do this; one of the most common is to
create individual vectors of data and then combine them into a data
frame using the `data.frame()` function.

Here's how this works. First, create a vector of names by inserting


four names into this code block between the quotation marks and then
run it:
```{r}
names <- c("", "", "", "")
```

Then create a vector of ages by adding four ages separated by commas


to the code chunk below. Make sure you are inputting numeric values
for the ages or you might get an error.

```{r}
age <- c(, , , )
```

With these two vectors, you can create a new data frame called
`people`:

```{r}
people <- data.frame(names, age)
```

## Step 3: inspect the data frame

Now that you have this data frame, you can use some different
functions to inspect it.

One common function you can use to preview the data is the `head()`
function, which returns the columns and the first several rows of
data. You can check out how the `head()` function works by running the
chunk below:

```{r}
head(people)
```

In addition to `head()`, there are a number of other useful functions


to summarize or preview your data. For example, the `str()` and
`glimpse()` functions will both provide summaries of each column in
your data arranged horizontally. You can check out these two functions
in action by running the code chunks below:

```{r}
str(people)
```

```{r}
glimpse(people)
```

You can also use `colnames()` to get a list the column names in your
data set. Run the code chunk below to check out this function:

```{r}
colnames(people)
```

Now that you have a data frame, you can work with it using all of the
tools in `R`. For example, you could use `mutate()` if you wanted to
create a new variable that would capture each person's age in twenty
years. The code chunk below creates that new variable:

```{r}
mutate(people, age_in_20 = age + 20)
```

## Step 4: Try it yourself

To get more familiar with creating and using data frames, use the code
chunks below to create your own custom data frame.

First, create a vector of any five different fruits. You can type
directly into the code chunk below; just place your cursor in the box
and click to type. Once you have input the fruits you want in your
data frame, run the code chunk.

```{r}

```

Now, create a new vector with a number representing your own personal
rank for each fruit. Give a 1 to the fruit you like the most, and a 5
to the fruit you like the least. Remember, the scores need to be in
the same order as the fruit above. So if your favorite fruit is last
in the list above, the score `1` needs to be in the last position in
the list below. Once you have input your rankings, run the code chunk.

```{r}

```

Finally, combine the two vectors into a data frame. You can call it
`fruit_ranks`. Edit the code chunk below and run it to create your
data frame.

```{r}

```

After you run this code chunk, it will create a data frame with your
fruits and rankings.

## Activity Wrap Up
In this activity, you learned how to create data frames, view them
with summary functions like `head()` and `glimpse()`, and then made
changes with the `mutate()` function. You can continue practicing
these skills by modifying the code chunks in the rmd file, or use this
code as a starting point in your own project console. As you explore
data frames, consider how they are similar and different to the tables
you have worked with in other data analysis tools like spreadsheets
and SQL. Data frames are one of the most basic building blocks you
will need to work with data in `R`. So understanding how to create and
work with data frames is an important first step to analyzing data.

Make sure to mark this activity as complete in Coursera.

Continuação
---
título: "Lição 2: Soluções de Dataframe"
saída: html_document
---

## Crie soluções de dataframe


Este documento contém as soluções para a atividade criar um data
frame. Você pode usar essas soluções para verificar seu trabalho e
garantir que seu código esteja correto ou solucionar problemas de seu
código se ele estiver retornando erros. Se você ainda não concluiu a
atividade, sugerimos que volte e a conclua antes de ler as soluções.

Caso ocorram erros, lembre-se de que você pode pesquisar na internet e


na comunidade do RStudio para obter ajuda:
https://community.rstudio.com/#

## Etapa 1: Carregar pacotes


Comece instalando o pacote necessário; neste caso, você vai querer
instalar `tidyverse`. Se você já instalou e carregou `tidyverse` nesta
sessão, sinta-se à vontade para pular os pedaços de código nesta
etapa.

```{r}
instalar.pacotes("tidyverse")
```
```{r}
biblioteca(tidyverse)
```

## Etapa 2: Criar quadro de dados

Às vezes, você precisará gerar um data frame diretamente no `R`. Há


várias maneiras de fazer isso; uma das mais comuns é criar vetores
individuais de dados e então combiná-los em um data frame usando a
função `data.frame()`.

Veja como isso funciona. Primeiro, crie um vetor de nomes:


```{r}
nomes <- c("Peter", "Jennifer", "Julie", "Alex")
```

Em seguida, crie um vetor de idades:

```{r}
idade <- c(15, 19, 21, 25)
```

Com esses dois vetores, você pode criar um novo quadro de dados
chamado `pessoas`:
```{r}
pessoas <- data.frame(nomes, idade)
```

## Etapa 3: inspecionar o quadro de dados

Agora que você tem esse quadro de dados, pode usar algumas funções
diferentes para inspecioná-lo.

Uma função comum que você pode usar para visualizar os dados é a
função `head()`, que retorna as colunas e as primeiras linhas de
dados. Você pode verificar como a função `head()` funciona executando
o pedaço abaixo:

```{r}
cabeça(pessoas)
```

Além de `head()`, há uma série de outras funções úteis para resumir ou


visualizar seus dados. Por exemplo, as funções `str()` e `glimpse()`
fornecerão resumos de cada coluna em seus dados organizados
horizontalmente. Você pode verificar essas duas funções em ação
executando os pedaços de código abaixo:

```{r}
str(pessoas)
```

```{r}
vislumbre(pessoas)
```

Você também pode usar `colnames()` para obter uma lista dos nomes de
colunas no seu conjunto de dados. Execute o pedaço de código abaixo
para verificar esta função:

```{r}
nomes de colunistas (pessoas)
```

Agora que você tem um data frame, pode trabalhar com ele usando todas
as ferramentas em `R`. Por exemplo, você pode usar `mutate()` se
quiser criar uma nova variável que capture a idade de cada pessoa em
vinte anos. O pedaço de código abaixo cria essa nova variável:

```{r}
mutate(pessoas, idade_em_20 = idade + 20)
```

## Etapa 4: Experimente você mesmo

Para se familiarizar mais com a criação e o uso de quadros de dados,


use os blocos de código abaixo para criar seu próprio quadro de dados
personalizado.

Primeiro, crie um vetor de quaisquer cinco frutas diferentes. Você


pode digitar diretamente no pedaço de código abaixo; basta colocar o
cursor na caixa e clicar para digitar. Depois de inserir as frutas que
deseja em seu quadro de dados, execute o pedaço de código.

```{r}
fruta <- c("Limão", "Mirtilo", "Toranja", "Manga", "Morango")
```

Agora, crie um novo vetor com um número representando sua


classificação pessoal para cada fruta. Dê 1 para a fruta que você mais
gosta e 5 para a fruta que você menos gosta. Lembre-se, as pontuações
precisam estar na mesma ordem da fruta acima. Então, se sua fruta
favorita estiver em último na lista acima, a pontuação `1` precisa
estar na última posição na lista abaixo. Depois de inserir suas
classificações, execute o pedaço de código.
```{r}
classificação <- c(4, 2, 5, 3, 1)
```

Por fim, combine os dois vetores em um data frame. Você pode chamá-lo
de `fruit_ranks`. Edite o pedaço de código abaixo e execute-o para
criar seu data frame.

```{r}
fruit_ranks <- data.frame(fruta, classificação)
```

Depois de executar esse pedaço de código, ele criará um quadro de


dados com suas frutas e classificações.

You might also like