h4sci / h4sci-tasks

Tasks and Exercises
7 stars 0 forks source link

Block 2, Task 3: Three R Ecosystems to Manipulate Data #7

Open mbannert opened 4 years ago

mbannert commented 4 years ago

This exercise lets you experience the different behavior of different ways to handle data. Run the following blocks of code separately. First run the baseR and discuss within your group what happens.

Analyze and evaluate different approaches.

# base R
basecars <- mtcars
basecars$eco <- FALSE
basecars[basecars$mpg > 22,"eco"] <- TRUE
basecars
# data.table
library(data.table)
dtcars <- as.data.table(mtcars)
dtcars[, eco := ifelse(mpg > 22, TRUE, FALSE)]
dtcars

# Bonus
# change the function and explore the
# effect of copy()
dtcars_2 <- as.data.table(mtcars)

f <- function(d){
  d[, eco := ifelse(mpg > 22, TRUE, FALSE)]
  message("Object modified in place")
}

f(dtcars_2)
dtcars_2
# dplyr aka tidyverse
library(dplyr)
mtcars %>% 
  mutate(eco = ifelse(mpg > 22, TRUE, FALSE))

mtcars