# welcome to week 3! # vectors! x <- 5 x weight_g <- c(50, 60, 65, 82) animals <- c("mouse", "rat", "dog") # class tells us the data type in a vector class(weight_g) class(animals) # str for structure str(weight_g) str(animals) # we can modify vectors with the c() function c(50, 60, 65, 82, 90) weight_g <- c(weight_g, 90) weight_g <- c(30, weight_g) weight_g 2L x <- 1:10 class(x) # coercion challenge num_char <- c(1, 2, 3, "a") class(num_char) num_char num_logical <- c(1, 2, 3, TRUE) class(num_logical) num_logical char_logical <- c("a", "b", "c", TRUE) class(char_logical) char_logical tricky <- c(1, 2, 3, "4") class(tricky) # challenge 2 combined_logical <- c(num_logical, char_logical) combined_logical class(combined_logical) # subsetting vectors animals <- c("mouse", "rat", "dog", "cat") animals[2] animals[c(3,2)] animals[c(3, 2, 4, 1, 2, 1)] animals[0] # conditional subsetting weight_g <- c(21, 34, 39, 54, 55) weight_g[c(TRUE, FALSE, TRUE, TRUE, FALSE)] weight_g > 50 weight_g[weight_g > 50] # multiple operations at once weight_g[weight_g < 30 | weight_g > 50] weight_g[weight_g >= 30 & weight_g == 21] animals animals[animals == "cat" | animals == "rat"] animals %in% c("mouse", "rat") animals[animals %in% c("mouse", "rat")] "four" > "five" "six" > "four" "eight" > "six" "alpha" > "beta" "dog" > "cat" # vector math x <- 1:10 x + 3 x * 10 y <- 100:109 x + y x y z <- 1:2 x z x + z z <- 1:3 x + z a <- x + z a x z str(x) str(z) length(x) length(z) # recycling with conditional subsetting x[c(TRUE, FALSE)] x[c(TRUE, FALSE, FALSE)] #Working with Missing Data #In R missing are represented as NAs heights <- c(2, 4, 4, NA, 6) mean(heights) max(heights) #na.rm = NA Remove mean(heights, na.rm = TRUE) max(heights, na.rm = TRUE) class(heights) #numeric, NA is not a character, R views it as a number (sort of) heights #is.na = Is it a NA? is.na(heights) #! = is not !is.na(heights) heights[!is.na(heights)] heights[is.na(heights)] #complete.cases = extracting all the elements that are complete cases (are not NAs) heights[complete.cases(heights)] #CHALLENGE! heights <- c(63, 69, 60, 65, NA, 68, 61, 70, 61, 59, 64, 69, 63, 63, NA, 72, 65, 64, 70, 63, 65) #remove the NAs heights2 <- heights[complete.cases(heights)] heights2 median(heights2) #longer than 67 inches length(heights2[heights2 > 67]) (heights2[heights2 > 67]) #Factors are a bit funky sex <- factor(c("male", "female", "female", "male")) class(sex) typeof(sex) levels(sex) nlevels(sex) #specify the order of the levels sex <- factor(sex, levels = c("male", "female")) sex #making factors into characters sex_ch <- as.character(sex)