-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfilter-control-preclass.Rmd
More file actions
103 lines (74 loc) · 1.95 KB
/
Copy pathfilter-control-preclass.Rmd
File metadata and controls
103 lines (74 loc) · 1.95 KB
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
---
title: "Blain Morin | Pre-Class #3"
output: html_document
---
### Question 1:
Using a loop, print the integers from 1 to 50.
```{r}
for (i in 1:50) {
print(i)
}
```
### Question 2:
A. Using a loop, add all the integers between 0 and 1000.
```{r}
y=0
for (i in 0:1000){
y = y +i
}
y
```
B. Now, add all the EVEN integers between 0 and 1000 (hint: use seq())
```{r}
z = 0
for (i in seq(from = 0, to = 1000, by = 2)) {
z = z + i
}
z
```
C. Now, repeat A and B WITHOUT using a loop.
```{r}
### A:
sum(1:1000)
### B:
sum(seq(0,1000, by = 2))
```
### Question 3:
Here is a dataframe of survey data containing 5 questions :
```{r}
survey <- data.frame(
"participant" = c(1, 2, 3, 4, 5, 6),
"q1" = c(5, 3, 2, 7, 11, 0),
"q2" = c(4, 2, 2, 5, -10, 99),
"q3" = c(-4, -3, 4, 2, 9, 10),
"q4" = c(-30, 5, 2, 23, 4, 2),
"q5" = c(88, 4, -20, 2, 4, 2)
)
```
The response to each question should be an integer between 1 and 5. Obviously, we have some bad values in the dataframe. The goal of this problem is to fix them.
A. Using a loop, create a new dataframe called survey.clean where all the invalid values (those that are not integers between 1 and 5) are set to NA.
```{r}
survey.clean = survey
for (i in 2:dim(survey.clean)[1]) {
vector = survey.clean [, i]
for (j in 1:length(vector)){
if (vector[j] > 5 | vector[j]< 1){
vector[j] = NA
} else {
vector[j] = vector[j]
}
}
survey.clean[, i] = vector
}
survey.clean
```
B. Now, again using a loop, add a new column to the dataframe called “invalid.answers” that indicates, for each participant, how many bad answers they gave.
```{r}
survey.clean2 = survey.clean
survey.clean2$invalid.answers = 0
for (i in 1:dim(survey.clean2[1])){
vector = survey.clean[i, ]
survey.clean2$invalid.answers[i] = sum(is.na(vector))
}
survey.clean2
```