-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_Data.R
More file actions
942 lines (650 loc) · 24.9 KB
/
01_Data.R
File metadata and controls
942 lines (650 loc) · 24.9 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
# ============================================================
# Working with Data in R
# Nevada Bioinformatics Center
# ============================================================
# OBJECTIVES:
# - Code in R
# - Understand R terms
# - Create a reproducible workflow
# - Work with built-in R datasets
# ============================================================
# CODING IN R
# ============================================================
# You can use R as a command line interface (CLI).
# A command is a way of giving the computer some information to perform a task.
# For example, like a calculator:
4 + 2
# addition
9 / 3
# ============================================================
# CREATING AND USING VARIABLES
# ============================================================
# One of the most powerful features of R is the ability to store values in
# variables (also called objects). This lets you save your work and reuse it later.
# --- Assignment Operator ---
# We use the assignment operator <- to store values in variables.
# Tip: In RStudio, press Alt + - (PC) or Option + - (Mac) to type <-
# Store a number in a variable
my_age <- 25
my_age
# Store text in a variable
my_name <- "Alex"
my_name
# Store the result of a calculation
total_score <- 85 + 92 + 78
total_score
new_test <- 45
# --- Using Variables in Calculations ---
# Once you've stored values in variables, you can use them in calculations.
# Store some values
price_per_item <- 15.50
number_of_items <- 4
tax_rate <- 0.08
# Calculate subtotal
subtotal <- price_per_item * number_of_items
subtotal
# Calculate tax
tax_amount <- subtotal * tax_rate
tax_amount
# Calculate final total
final_total <- subtotal + tax_amount
final_total
# --- Variables Don't Update Automatically ---
# Unlike spreadsheets, R variables are STATIC -- they only change when you
# explicitly tell them to.
# Initial calculation
base_price <- 100
discount <- 0.10
discounted_price <- base_price * (1 - discount)
discounted_price
# Change the base price
base_price <- 200
# discounted_price is still based on the old value!
discounted_price
# You need to recalculate it
discounted_price <- base_price * (1 - discount)
discounted_price
# --- Variable Naming Rules ---
# Good variable names make your code easier to understand.
# Good variable names
student_count <- 30
average_grade <- 87.5
experiment_start_date <- "2024-01-15"
# Less clear variable names (but still valid)
x <- 30
avg <- 87.5
d <- "2024-01-15"
# Rules for naming variables:
# - Can contain letters, numbers, dots (.), and underscores (_)
# - Cannot start with a number
# - Cannot contain spaces
# - Case-sensitive (Age and age are different variables)
# - Avoid using names of existing R functions (mean, sum, data, T, F, etc.)
# --- Why Use Variables? ---
# Variables make your code: readable, reusable, maintainable, and less error-prone.
# Without variables (hard to read and maintain)
final_grade <- (85 + 92 + 78 + 88) / 4 * 0.6 + 95 * 0.4
final_grade
ls() # list all objects in your environment
# With variables (much clearer!)
exam1 <- 85
exam2 <- 92
exam3 <- 78
exam4 <- 88
final_exam <- 95
exam_average <- (exam1 + exam2 + exam3 + exam4) / 4
exam_weight <- 0.6
final_weight <- 0.4
final_grade <- (exam_average * exam_weight) + (final_exam * final_weight)
final_grade
# ============================================================
# FUNCTIONS AND THEIR ARGUMENTS
# ============================================================
# Functions are pre-written pieces of code that perform specific tasks.
# They're like recipes -- give them ingredients (arguments), get back a result.
#
# Basic function structure:
# function_name(argument1, argument2, ...)
# Print a message
print("Hello, world!")
# --- Simple Functions ---
# Square root function
sqrt(16)
sqrt(25)
# Absolute value
abs(-5)
abs(3.2)
# Round numbers
round(3.14159)
round(2.718)
# --- Functions with Multiple Arguments ---
# Round to specific decimal places
round(3.14159, digits = 2)
round(2.718281, digits = 3)
# Exclude NA's from mean
test_scores <- c(87, 93, 75, NA, 84)
mean(test_scores, na.rm = TRUE)
# --- Getting Help with Functions ---
?round # Get help on the round function
args(round) # See what arguments a function takes
# args(round) tells us:
# x = the number(s) to round
# digits = how many decimal places (default is 0)
# --- Named vs. Positional Arguments ---
# You can provide arguments by position or by name.
# Positional arguments (order matters)
round(3.14159, 2)
# Named arguments (order doesn't matter)
round(digits = 2, x = 3.14159)
round(x = 3.14159, digits = 2)
# Best practice: use names for optional arguments to make code clearer.
# You can always press Tab to list argument options in RStudio.
# ============================================================
# HOW R VIEWS DATA
# ============================================================
# R organizes information into different types of data structures.
# Understanding these structures is key to working effectively with R.
# --- Single Values (Scalars) ---
# The simplest data structure is a single value.
# Numbers
my_number <- 42
my_number
# Text (character strings)
my_name <- "Nevada Bioinformatics"
my_name
# Logical values (TRUE/FALSE)
my_logical <- TRUE
my_logical
# --- Vectors ---
# A vector is a collection of values of the same type.
# Vectors are the building blocks of R.
# Numeric vector
ages <- c(25, 30, 35, 40)
ages
# Character vector
names <- c("Alice", "Bob", "Charlie", "Diana")
names
# Logical vector
passed_exam <- c(TRUE, FALSE, TRUE, TRUE)
passed_exam
# The c() function combines values into a vector.
# Use quotes for text, but NOT for numbers or logical values.
# --- Data Frames ---
# A data frame is like a spreadsheet -- rows and columns where each column
# can be a different type of data.
# Create a simple data frame
student_data <- data.frame(
name = c("Alice", "Bob", "Charlie"),
age = c(25, 30, 35),
passed = c(TRUE, FALSE, TRUE)
)
student_data
# --- Lists ---
# A list can hold different types of objects, including other lists.
my_list <- list(
numbers = c(1, 2, 3),
text = "Hello World",
data = student_data
)
my_list
# --- Matrices ---
# A matrix is like a data frame but all values must be the same type.
my_matrix <- matrix(1:9, nrow = 3, ncol = 3)
my_matrix
# --- Checking Data Types ---
# R provides functions to check what type of data structure you're working with.
class(ages) # "numeric"
class(names) # "character"
class(student_data) # "data.frame"
str(student_data) # Structure of the object
is.vector(ages) # TRUE
is.data.frame(ages) # FALSE
# This works -- adding numbers
numbers <- c(1, 2, 3, 4)
sum(numbers)
# This would give an error -- trying to add text
# text <- c("a", "b", "c")
# sum(text)
# --- Functions with Vectors ---
# Most R functions work with vectors (multiple values at once).
numbers <- c(1.167, 2.873, 3.994, 4.225, 5.861)
numbers
round(numbers)
round(numbers, digits = 1)
sqrt(numbers)
# --- Statistical Functions ---
grades <- c(85, 92, 78, 88, 95, 82, 90)
grades
mean(grades) # average
median(grades) # middle value
max(grades) # highest value
min(grades) # lowest value
length(grades) # count of values
sum(grades) # total
# --- Functions That Create Data ---
seq(1, 10) # numbers from 1 to 10
seq(1, 10, by = 2) # every 2nd number from 1 to 10
seq(0, 1, by = 0.1) # decimals from 0 to 1
rep(5, times = 3) # repeat 5 three times
rep(c(1, 2), times = 4) # repeat the vector 1,2 four times
# The colon operator (:) is a shortcut for consecutive integer sequences.
# It's much faster to type 1:5 than c(1, 2, 3, 4, 5) or seq(1, 5).
1:5
c(1, 2, 3, 4, 5)
seq(1, 5)
10:1 # counts down: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
# --- Combining Functions ---
# You can use the output of one function as input to another.
numbers <- c(1, 4, 9, 16, 25)
sqrt_numbers <- sqrt(numbers)
sqrt_numbers
mean_of_sqrt <- mean(sqrt_numbers)
mean_of_sqrt
# Or do it all in one line
result <- mean(sqrt(c(1, 4, 9, 16, 25)))
result
# ============================================================
# EXERCISES -- BASIC FUNCTIONS
# ============================================================
# Exercise 1: Basic Functions
# 1. Calculate the square root of 144
# Your code here:
# 2. Round 2.718281828 to 4 decimal places
# Your code here:
# 3. Find the absolute value of -15.7
# Your code here:
# Exercise 2: Working with Vectors
test_scores <- c(78, 85, 92, 88, 76, 95, 82, 90, 87, 79)
# 1. Calculate the mean of test_scores
# Your code here:
# 2. Find the highest score
# Your code here:
# 3. Find the lowest score
# Your code here:
# 4. Count how many scores there are
# Your code here:
# 5. Round the square root of all test scores to 2 digits
# Your code here:
# --- Solutions ---
# Exercise 1 Solutions
sqrt(144) # 12
round(2.718281828, digits = 4) # 2.7183
abs(-15.7) # 15.7
# Exercise 2 Solutions
mean(test_scores) # 85.2
max(test_scores) # 95
min(test_scores) # 76
length(test_scores) # 10
round(sqrt(test_scores), digits = 2) # square root of each score, rounded
# ============================================================
# WORKING WITH DATA
# ============================================================
# ---- Built-in R Datasets ----
# R comes with many built-in datasets that are perfect for learning.
# They are already loaded -- no need to download or import anything!
# See all available built-in datasets:
data()
# Some popular built-in datasets:
# mtcars -- Car performance data (32 cars, 11 variables)
# iris -- Flower measurements (150 flowers, 5 variables)
# airquality -- Air quality measurements in New York
# PlantGrowth -- Plant growth under different conditions
# --- Loading and Exploring a Dataset ---
# Let's work with the mtcars dataset.
data(mtcars) # Loads dataset into your Environment in RStudio
head(mtcars) # First few rows
str(mtcars) # Structure
summary(mtcars) # Summary statistics
?mtcars # Help page -- describes all variables
# The mtcars dataset: 32 cars from 1974 Motor Trend magazine.
# mpg = Miles per gallon
# cyl = Number of cylinders
# hp = Horsepower
# wt = Weight (1000 lbs)
# ...and more
# --- Exploring the Dataset ---
mtcars # Print the whole dataset
dim(mtcars) # Dimensions (rows and columns)
nrow(mtcars) # Number of rows
ncol(mtcars) # Number of columns
names(mtcars) # Column names
head(mtcars, n = 15) # First 15 rows
tail(mtcars) # Last few rows
str(mtcars) # Structure
summary(mtcars) # Summary statistics
# ============================================================
# ACCESSING COLUMNS IN DATA FRAMES
# ============================================================
# Before we explore datasets, we need to know how to access specific columns.
# Data frames have rows (observations) and columns (variables).
# --- The $ Operator ---
# The $ operator extracts a specific column from a data frame.
# Syntax: dataframe_name$column_name
# This returns the column as a vector you can use with functions.
mtcars$mpg # miles per gallon
mtcars$cyl # number of cylinders
mean(mtcars$mpg) # average miles per gallon
max(mtcars$hp) # maximum horsepower
min(mtcars$wt) # minimum weight
# ============================================================
# SUBSETTING DATA FRAMES
# ============================================================
# Subsetting means selecting specific parts of your data --
# certain rows, certain columns, or both.
# It's like filtering in a spreadsheet, but much more flexible.
# --- Understanding Bracket Notation ---
# Data frames use [row, column] to specify which parts you want.
#
# [1, ] = first row, all columns
# [, 2] = all rows, second column
# [1:5, c(1,3)] = first 5 rows, columns 1 and 3
#
# Leave a side blank to mean "give me all of them."
# --- Selecting Columns ---
mtcars$mpg # Using $
mtcars[, "mpg"] # Using brackets with column name
mtcars[, 1] # Using brackets with column position
mtcars[, c("mpg", "hp")] # Multiple columns by name
mtcars[, c(1, 4)] # Multiple columns by position
# --- Selecting Rows ---
mtcars[1, ] # First row, all columns
mtcars[1:5, ] # First 5 rows, all columns
mtcars[c(1, 3, 5), ] # Rows 1, 3, and 5, all columns
# --- Selecting Rows and Columns Together ---
mtcars[1:5, c("mpg", "hp")] # First 5 rows, mpg and hp columns
mtcars[1:3, 1:3] # First 3 rows and first 3 columns
# --- Conditional Subsetting ---
# Select rows based on conditions.
# A logical test returns TRUE or FALSE for each row;
# R keeps only the rows where the test is TRUE.
# Comparison operators:
# == equal to (use TWO equals signs for comparison!)
# != not equal to
# > greater than
# < less than
# >= greater than or equal to
# <= less than or equal to
# Simple example
test_values <- c(5, 10, 15, 20)
test_values
test_values > 10 # Which values are greater than 10? Returns TRUE/FALSE
test_values == 15 # Which values equal exactly 15? Returns TRUE/FALSE
# IMPORTANT: Use == (two equals) for comparison, not = (one equals).
# Single = is for assignment (like <-).
# --- Basic Conditional Subsetting ---
# Cars with more than 20 miles per gallon
mtcars$mpg > 20 # TRUE/FALSE for each car
high_mpg_cars <- mtcars[mtcars$mpg > 20, ]
head(high_mpg_cars)
# Cars with exactly 4 cylinders
four_cyl_cars <- mtcars[mtcars$cyl == 4, ]
nrow(four_cyl_cars) # How many 4-cylinder cars?
# --- Logical Operators for Multiple Conditions ---
#
# & AND -- both conditions must be true
# | OR -- at least one condition must be true
# ! NOT -- reverses TRUE/FALSE
# AND (&): Cars with high mpg AND low weight
efficient_cars <- mtcars[mtcars$mpg > 25 & mtcars$wt < 3, ]
efficient_cars
nrow(efficient_cars)
# OR (|): Cars that are either very powerful OR very efficient
powerful_or_efficient <- mtcars[mtcars$hp > 200 | mtcars$mpg > 25, ]
nrow(powerful_or_efficient)
sum(mtcars$hp > 200) # Cars with >200 hp
table(mtcars$hp > 200)
sum(mtcars$mpg > 25) # Cars with >25 mpg
# NOT (!): Cars that are NOT 4-cylinder
not_four_cyl <- mtcars[!(mtcars$cyl == 4), ]
# Same result using !=
not_four_cyl_alt <- mtcars[mtcars$cyl != 4, ]
# --- Complex Conditions ---
# Combine multiple operators; use parentheses to control order of operations.
# Cars with good fuel economy (>20 mpg) that are either lightweight (<3)
# OR have low horsepower (<100 hp)
complex_condition <- mtcars[mtcars$mpg > 20 & (mtcars$wt < 3 | mtcars$hp < 100), ]
head(complex_condition)
# Note the parentheses!
# Without: mpg > 20 & wt < 3 | hp < 100 means (mpg > 20 & wt < 3) OR hp < 100
# With: mpg > 20 & (wt < 3 | hp < 100) means mpg > 20 AND (wt < 3 OR hp < 100)
# --- Working with Text / Factor Conditions ---
data(iris)
# Flowers of a specific species
setosa_flowers <- iris[iris$Species == "setosa", ]
head(setosa_flowers)
# Flowers that are NOT setosa
not_setosa <- iris[iris$Species != "setosa", ]
head(not_setosa)
# Multiple species using OR
setosa_or_versicolor <- iris[iris$Species == "setosa" | iris$Species == "versicolor", ]
head(setosa_or_versicolor)
# --- The %in% Operator ---
# Check if values match any item in a list -- cleaner than long OR chains.
# Instead of:
# iris[iris$Species == "setosa" | iris$Species == "versicolor", ]
# Use %in%:
selected_species <- iris[iris$Species %in% c("setosa", "versicolor"), ]
head(selected_species)
# Also works with numbers:
# Cars with 4 or 8 cylinders
common_cylinders <- mtcars[mtcars$cyl %in% c(4, 8), ]
table(common_cylinders$cyl)
# --- Useful Functions for Subsetting ---
# which() -- Finding Positions
# Returns the row numbers where a condition is TRUE (instead of TRUE/FALSE values).
mtcars$cyl > 6 # Returns TRUE/FALSE for each car
which(mtcars$cyl > 6) # Returns the row numbers where it's TRUE
high_cyl_positions <- which(mtcars$cyl > 6)
mtcars[high_cyl_positions, c("mpg", "cyl", "hp")]
# which.max() and which.min() -- Finding Extremes
# Returns the position of the maximum or minimum value.
which.max(mtcars$mpg) # Position number
mtcars[which.max(mtcars$mpg), ] # The actual car data
rownames(mtcars)[which.max(mtcars$mpg)] # Just the car name
# Find the heaviest car
mtcars[which.max(mtcars$wt), c("wt", "mpg", "hp")]
# When to use each:
# Regular subsetting -- all rows meeting a condition
# which() -- specific row positions
# which.max()/which.min() -- single best/worst case
# ============================================================
# FACTORS AND LEVELS
# ============================================================
# Factors are R's way of handling categorical data (like groups or categories).
# They look like text but are stored differently and are useful for
# analysis and plotting.
#
# Real-world examples of categorical data:
# Survey responses (agree / disagree / neutral)
# Treatment groups (control / treatment)
# Geographic regions (north / south / east / west)
# Product ratings (poor / fair / good / excellent)
# --- What Makes Factors Special? ---
#
# 1. Factors have a specific order -- you control how categories appear
# in plots and tables
# 2. Statistical functions expect factors for categorical data
# 3. Factors save memory -- R stores each category name only once
# Create a simple factor
car_sizes <- factor(c("small", "medium", "large", "small", "large", "medium"))
car_sizes
levels(car_sizes) # See the categories
str(car_sizes) # Notice R stores the data as numbers behind the scenes!
# --- Working with the iris Dataset ---
data(iris)
head(iris)
str(iris)
# The Species column is already a factor
iris$Species
levels(iris$Species)
# Count occurrences of each species
table(iris$Species)
# Simple bar plot
barplot(table(iris$Species))
# --- Converting Character Data to Factor ---
colors <- c("red", "blue", "green", "red", "blue")
colors
colors_factor <- as.factor(colors)
colors_factor
levels(colors_factor) # Notice alphabetical order
# --- Handling Missing Data with Factors ---
survey_responses <- c("agree", "disagree", "neutral", NA, "agree", NA, "disagree")
survey_responses
survey_factor <- as.factor(survey_responses)
survey_factor
levels(survey_factor) # NA is NOT a level
table(survey_factor)
table(survey_factor, useNA = "ifany") # Include NAs in count
# Or, replace NAs with "unknown" using is.na():
survey_responses[is.na(survey_responses)] <- "unknown"
survey_responses
survey_clean <- as.factor(survey_responses)
survey_clean
levels(survey_clean)
# --- Reordering Factor Levels ---
# Factors are automatically leveled in alphabetical order.
# You can change the order by specifying it explicitly.
sizes <- factor(c("small", "large", "medium", "small", "medium", "large"))
levels(sizes) # Alphabetical order by default
# Reorder levels logically
sizes_ordered <- factor(sizes, levels = c("small", "medium", "large"))
levels(sizes_ordered)
# --- Working with Factors in a Dataset ---
str(mtcars)
# Convert the transmission variable (am) to a factor with descriptive labels.
# am: 0 = automatic, 1 = manual
table(mtcars$am) # See current values
mtcars$am <- factor(mtcars$am,
levels = c(1, 0), # manual first, then automatic
labels = c("manual", "automatic")) # descriptive names
str(mtcars$am)
levels(mtcars$am)
table(mtcars$am)
barplot(table(mtcars$am))
# ============================================================
# BASIC PLOTTING IN R
# ============================================================
# R has built-in functions for creating simple plots.
# --- Scatter Plots with plot() ---
# Shows relationships between two variables.
# Basic scatter plot
plot(mtcars$hp, mtcars$mpg)
# Add labels and title
plot(mtcars$hp, mtcars$mpg,
main = "Fuel Efficiency vs Horsepower", # Main title
xlab = "Horsepower", # X-axis label
ylab = "Miles per Gallon") # Y-axis label
# --- Bar Plots with barplot() ---
# Often used with table() to show counts.
table(mtcars$cyl) # Count how many cars have each number of cylinders
barplot(table(mtcars$cyl))
# Add labels
barplot(table(mtcars$cyl),
main = "Number of Cars by Cylinder Count",
xlab = "Cylinders",
ylab = "Count")
# ============================================================
# EXERCISE -- DATA ANALYSIS PRACTICE
# ============================================================
# How to approach these exercises:
# - Try each one on your own first
# - Don't worry about making mistakes -- that's how you learn!
# - If you get stuck, re-read the relevant section above
# - There's often more than one correct way to solve a problem in R
# - Tip: type out the code rather than copy-pasting
# 1. Load the mtcars dataset and explore it:
# - Load with data(mtcars)
# - Look at the first 6 rows
# - Check the structure
# - Get summary statistics
# 2. Answer these questions using R code:
# a. How many cars have more than 6 cylinders?
# b. What is the average horsepower of cars with automatic transmission? (am == 0)
# c. Which car has the best fuel efficiency (highest mpg)?
# d. Create a subset of cars with >25 mpg AND weight <3
# 3. Work with factors:
# - Convert the gear variable to a factor
# - Count how many cars have each number of gears
# - Create a bar plot of the gear distribution
# --- Solutions ---
# Load and explore
data(mtcars)
head(mtcars)
str(mtcars)
summary(mtcars)
# a. How many cars have more than 6 cylinders?
cars_over_6_cyl <- mtcars[mtcars$cyl > 6, ]
nrow(cars_over_6_cyl)
# Alternative: sum(mtcars$cyl > 6)
# b. Average horsepower of automatic cars
automatic_cars <- mtcars[mtcars$am == 0, ]
mean(automatic_cars$hp)
# Alternative: mean(mtcars$hp[mtcars$am == 0])
# c. Car with best fuel efficiency
best_mpg_car <- mtcars[which.max(mtcars$mpg), ]
rownames(best_mpg_car)
best_mpg_car$mpg
# d. Efficient and lightweight cars
efficient_light <- mtcars[mtcars$mpg > 25 & mtcars$wt < 3, ]
nrow(efficient_light)
rownames(efficient_light)
# e. Work with factors
mtcars$gear <- as.factor(mtcars$gear)
table(mtcars$gear)
barplot(table(mtcars$gear),
main = "Number of Cars by Gear Count",
xlab = "Number of Gears",
ylab = "Count")
# ============================================================
# BONUS CHALLENGE (OPTIONAL)
# ============================================================
# 1. Find the car with the highest horsepower-to-weight ratio
# 2. Create a new variable efficiency_category:
# "High" = >25 mpg
# "Medium" = 15-25 mpg
# "Low" = <15 mpg
# 3. Count how many cars fall into each category
# --- Bonus Solutions ---
# 1. Highest horsepower-to-weight ratio
mtcars$hp_to_weight <- mtcars$hp / mtcars$wt
best_ratio_car <- mtcars[which.max(mtcars$hp_to_weight), ]
rownames(best_ratio_car)
best_ratio_car$hp_to_weight
# 2. Create efficiency categories
mtcars$efficiency_category <- "Low" # Start all cars as "Low"
mtcars$efficiency_category[mtcars$mpg >= 15 & mtcars$mpg <= 25] <- "Medium"
mtcars$efficiency_category[mtcars$mpg > 25] <- "High"
# Convert to factor with logical order
mtcars$efficiency_category <- factor(mtcars$efficiency_category,
levels = c("Low", "Medium", "High"))
# 3. Count cars in each category
table(mtcars$efficiency_category)
# ============================================================
# GETTING HELP
# ============================================================
# In R: ?function_name (e.g., ?mean)
# In RStudio: Press F1 while cursor is on a function name
# Datasets: ?dataset_name (e.g., ?mtcars)
# Online: Stack Overflow, RStudio Community, R documentation
# Errors: Read them carefully -- they often tell you exactly what's wrong!
# ============================================================
# KEY TAKEAWAYS
# ============================================================
# R fundamentals:
# Use R as a calculator, store values with <-, understand data structures
# (vectors, data frames, lists, matrices)
# Functions and arguments:
# Use built-in functions like mean(), sum(), sqrt() with named/positional
# arguments; get help with ?function_name
# Data exploration:
# Access built-in datasets with data(), explore with head(), str(), summary(),
# extract columns with $
# Data subsetting:
# Select rows/columns with [row, column], filter with conditions using
# ==, >, &, |, find extremes with which.max()
# Factors for categories:
# Convert text to factors with as.factor(), control level order,
# handle missing data; essential for plotting and analysis
# Best practices:
# Write code in scripts with comments (#), use descriptive variable names,
# organize projects, read error messages carefully