# # Practice 1 # # option 1 - convenient step-by-step way name <- c("Jose","Sara","Maria","Frank","John") age <- c(17,22,21,21,18) sex <- c("male","female","female","male","male") econ_scale <- c(-3,0.6,2,-3,3.1) soc_scale <- c(-7.2,0.2,0,0.5,3) practice1_df <- data.frame(name, age, sex, econ_scale, soc_scale) str(practice1_df) # option 2 - one-command way practice1_df <- data.frame(name = c("Jose","Sara","Maria","Frank","John"), age = c(17,22,21,21,18), sex = c("male","female","female","male","male"), econ_scale = c(-3,0.6,2,-3,3.1), soc_scale = c(-7.2,0.2,0,0.5,3) ) # # Practice 2 # install.packages("psych") library("psych") dim(practice1_df) head(practice1_df) str(practice1_df) describe(practice1_df) # it throws some errors at us. Not all errors are wrong. These errors are useful, as they warn us about the character class of variables "name" and "sex". It's not a bug, it's a feature. # # Practice 3 # # Load a default dataset called “eurodist” / Visually inspect the data source eurodist # Figure out the type of the data source str(eurodist) class(eurodist) # Transform data source to most suitable format for data manipulation as.matrix(eurodist) ed.matrix <- as.matrix(eurodist) # don't forget, you always have to save the result = create new object in the environment # # Practice 4 # # Create a matrix with following parameters # 6 by 6 layout # Contains numbers 0 and 1 in a 0 1 0 1 0 1 0 1 pattern # The pattern is organized by rows # option 1 - the most transparent approach size <- 6 * 6 # create the size object pattern <- c(0,1) # create the repeating pattern pattern.length <- length(pattern) # get the number of elements in the repeating pattern (length) repetitions <- size/pattern.length # get the number of pattern repetitions help(rep) # get the list of arguments in the rep() function mat.data <- rep(pattern,times = repetitions) # create the matrix pattern matrix(data = mat.data,nrow = 6,ncol = 6) # create the matrix. Oops - it is organized by columns, not by rows matrix(data = mat.data,nrow = 6,ncol = 6,byrow = TRUE) # use the argument "byrow" to change the direction result.matrix <- matrix(data = mat.data,nrow = 6,ncol = 6,byrow = TRUE) # save result in the environment # option 2 - the lazy/proficient approach matrix(data = rep(x = c(0,1),18),nrow = 6, ncol = 6, byrow = TRUE) result.matrix <- matrix(data = rep(x = c(0,1),18),nrow = 6, ncol = 6, byrow = TRUE)