Commit b70b2f57 authored by Arndt Leininger's avatar Arndt Leininger

mutate_at instead of apply in exercise

parent e627a103
......@@ -19,7 +19,7 @@ output:
```{r showInstructor, echo=FALSE}
###########################################
showInstruct = TRUE # Set to TRUE to produce instructor output.
showInstruct = FALSE # Set to TRUE to produce instructor output.
# Set FALSE for student version
############################################
```
......@@ -127,7 +127,9 @@ e$csu1 <- e$csu2 <- NULL
**8. Convert the party variables from counts to percentages.**
```{r 1-8, echo=TRUE, eval=showInstruct}
e[, 6:ncol(e)] <- e[, 6:ncol(e)] %>% apply(2, function(x) x/e$voters * 100 %>% round(2))
e <-
e %>%
mutate_at(vars(cducsu1:afd2), function(x) x/e$voters * 100 %>% round(2))
```
**9. Create a variable called turnout which contains, well, electoral turnout.**
......@@ -231,15 +233,17 @@ s <- s %>% select(one_of(new))
s <- s %>% filter(no < 900 & !is.na(no))
```
**5. Convert any numeric variables that have been interpreted as strings into numeric variables. Use a loop to do this (Hint: Check out `apply()` which allows you to loop over the columns of a data.frame)**
**5. Convert any numeric variables that have been interpreted as strings into numeric variables. Use a loop to do this (Hint: Check out `mutate_at()` which allows you to manipulate multiple variables at the same time with the same fuction.)**
```{r 2-5, echo=TRUE, eval=showInstruct}
glimpse(s) # are any variables characters although they should be numeric?
# remove spaces and replace comma with decimal point and make variable numeric
s[, 4:ncol(s)] <- apply(s[, 4:ncol(s)], 2, str_replace, ' ', '') %>%
apply(2, str_replace, ',', '.') %>% as.numeric
s <-
s %>% mutate_at(vars(area:socialbenefits), str_replace, ' ', '') %>%
mutate_at(vars(area:socialbenefits), str_replace, ',', '.') %>%
mutate_at(vars(area:socialbenefits), as.numeric)
glimpse(s)
```
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment