-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdataframe.Rmd
57 lines (44 loc) · 1.2 KB
/
dataframe.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
## Data frames
A data frame is a 2-dimensional structure.
<br> It is more general than a matrix.
<br><br>
All columns in a data frame:
+ can be of different **types** (numeric, character or logical)
+ must have the same **length**
### Create a data frame
* With the **data.frame** function:
```{r}
# stringsAsFactors: ensures that characters are treated as characters and not as factors
d <- data.frame(c("Maria", "Juan", "Alba"),
c(23, 25, 31),
c(TRUE, TRUE, FALSE),
stringsAsFactors = FALSE)
```
* Example why "stringsAsFactors = FALSE" is useful
```{r}
# Create a data frame with default parameters
df <- data.frame(label=rep("test",5), column2=1:5)
# Replace one value
df[2,1] <- "yes"
# Throws an error and doesn't replace the value !
```
```{r}
# Create a data frame with
df2 <- data.frame(label=rep("test",5), column2=1:5, stringsAsFactors = FALSE)
# Replace one value
df2[2,1] <- "yes"
# Works!
```
* Converting a matrix into a data frame:
```{r}
# create a matrix
b <- matrix(c(1, 0, 34, 44, 12, 4),
nrow=3,
ncol=2)
# convert as data frame
b_df <- as.data.frame(b)
```
### Data frame manipulation:
<br>
Very similar to matrix manipulation.
<img src="images/df_fetch.png" width="450"/>