← R EnglishChapter 02 of 13

Variables and Data Types

## Learning Objectives - Declare and work with variables - Understand R's atomic data types - Master vectors and vector operations - Work with matrices and dataframes - Understand type conversion ## Variables ### Assignment ```r # Using assignment operator (preferred) x <- 10 name <- "Alice" is_valid <- TRUE # Using equals sign y = 20 # Print value x print(x) ``` ### Naming Rules - Start with letter or dot (not digit) - Can contain letters, numbers, underscores, dots - Case-sensitive - Cannot use reserved words ```r # Valid variable names my_var <- 5 myVar <- 5 MY_VAR <- 5 .myvar <- 5 # Starting with dot is valid myvar2 <- 5 # Reserved words to avoid # if, else, for, while, function, TRUE, FALSE, NULL ``` ## Atomic Data Types ### Numeric ```r # Double precision (default) x <- 3.14 class(x) # "numeric" # Integer (with L suffix) y <- 5L class(y) # "integer" # Check type is.numeric(x) # TRUE is.integer(y) # FALSE for 5L (it's integer) is.integer(5) # FALSE (5 is numeric by default) ``` ### Character (Strings) ```r # String assignment name <- "Alice" greeting <- 'Hello' # Check type class(name) # "character" is.character(name) # TRUE ``` ### Logical (Boolean) ```r # Logical values (uppercase) is_active <- TRUE has_permission <- FALSE # Can also use T and F (but avoid in scripts) is_valid <- T is_invalid <- F # Check type class(is_active) # "logical" is.logical(is_active) # TRUE ``` ### Special Values ```r # NULL - absence of value x <- NULL is.null(x) # TRUE # NA - missing value x <- NA is.na(x) # TRUE # NaN - not a number x <- 0 / 0 is.nan(x) # TRUE # Inf - infinity x <- 1 / 0 is.infinite(x) # TRUE # Check for NA specifically x <- c(1, 2, NA, 4) is.na(x) # FALSE FALSE TRUE FALSE ``` ## Vectors ### Creating Vectors ```r # Using c() function (combine) nums <- c(1, 2, 3, 4, 5) letters <- c("a", "b", "c") # Using colon operator 1:5 # c(1, 2, 3, 4, 5) # Using seq() seq(1, 10, by = 2) # 1, 3, 5, 7, 9 seq(1, 10, length.out = 5) # 1, 3.25, 5.5, 7.75, 10 # Using rep() rep(1, 5) # c(1, 1, 1, 1, 1) rep(c(1, 2), 3) # c(1, 2, 1, 2, 1, 2) rep(c(1, 2), each = 3) # c(1, 1, 1, 2, 2, 2) ``` ### Vector Operations ```r # Arithmetic operations (element-wise) c(1, 2, 3) + c(4, 5, 6) # c(5, 7, 9) c(1, 2, 3) * 2 # c(2, 4, 6) # Recycling (shorter vector recycled) c(1, 2) + c(10, 20, 30, 40) # Warning: longer object length not multiple of shorter # Comparison c(1, 2, 3) > 2 # FALSE FALSE TRUE c(1, 2, 3) == 2 # FALSE TRUE FALSE ``` ### Vector Indexing ```r vec <- c(10, 20, 30, 40, 50) # By position (1-indexed) vec[1] # First element: 10 vec[3] # Third element: 30 vec[1:3] # First three: 10, 20, 30 # Negative indexing (exclude) vec[-1] # All except first: 20, 30, 40, 50 vec[-c(1, 3)] # Exclude 1st and 3rd: 20, 40, 50 # Logical indexing vec[vec > 25] # Elements > 25: 30, 40, 50 # By name named_vec <- c(a = 1, b = 2, c = 3) named_vec["a"] # 1 ``` ### Vector Functions ```r vec <- c(3, 1, 4, 1, 5, 9, 2, 6) length(vec) # 8 sum(vec) # Sum: 31 prod(vec) # Product mean(vec) # Mean: 3.875 sd(vec) # Standard deviation var(vec) # Variance # Sorting sort(vec) # Ascending sort(vec, decreasing = TRUE) # Descending # Unique values unique(c(1, 2, 2, 3, 3, 3)) # 1, 2, 3 # Count occurrences table(c("a", "b", "a", "c", "a")) # a b c # 3 1 1 ``` ## Matrices ### Creating Matrices ```r # By row/column binding row1 <- c(1, 2, 3) row2 <- c(4, 5, 6) mat <- rbind(row1, row2) # 2x3 matrix mat2 <- cbind(c(1, 2), c(3, 4), c(5, 6)) # 2x3 matrix # Using matrix() mat <- matrix(1:6, nrow = 2, ncol = 3) mat <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE) ``` ### Matrix Operations ```r mat <- matrix(1:4, nrow = 2) mat2 <- matrix(5:8, nrow = 2) # Element-wise mat + mat2 mat * mat2 # Element-wise multiplication # Matrix multiplication (%*%) mat %*% t(mat2) # Transpose t(mat) # Dimensions nrow(mat) ncol(mat) dim(mat) ``` ### Matrix Indexing ```r mat <- matrix(1:9, nrow = 3) mat[1, 2] # Row 1, Column 2 mat[1, ] # Entire first row mat[, 2] # Entire second column mat[1:2, 2:3] # Submatrix ``` ## Lists ### Creating Lists ```r # Create a list with different types my_list <- list( name = "Alice", age = 30, scores = c(95, 87, 92), is_student = TRUE ) # Empty list empty_list <- list() ``` ### List Operations ```r my_list <- list(name = "Alice", age = 30) # Access by name my_list$name # "Alice" my_list[["name"]] # "Alice" # Access by index my_list[[1]] # "Alice" # Get all names names(my_list) # "name" "age" ``` ### Convert List to Vector ```r # Unlist flattens to vector unlist(list(1, 2, 3)) # c(1, 2, 3) ``` ## Dataframes ### Creating Dataframes ```r # Create from vectors df <- data.frame( name = c("Alice", "Bob", "Charlie"), age = c(25, 30, 35), score = c(95.5, 87.3, 92.1) ) # Check structure str(df) # 'data.frame': 3 obs. of 3 variables # View View(df) head(df) tail(df) ``` ### Dataframe Indexing ```r df <- data.frame( name = c("Alice", "Bob", "Charlie"), age = c(25, 30, 35) ) # By column name df$name # "Alice" "Bob" "Charlie" df[, "name"] # Same # By position df[, 1] # First column df[1, ] # First row # Using subset subset(df, age > 25) ``` ## Type Conversion ### Checking Types ```r x <- 5 is.numeric(x) # TRUE is.integer(x) # FALSE is.character(x) # FALSE is.logical(x) # FALSE is.vector(x) # TRUE ``` ### Converting Types ```r # To character as.character(5) # "5" as.character(TRUE) # "TRUE" # To numeric as.numeric("5") # 5 as.numeric("hello") # NA with warning as.numeric(TRUE) # 1 as.numeric(FALSE) # 0 # To integer as.integer(5.7) # 5 # To logical as.logical(1) # TRUE as.logical(0) # FALSE as.logical("TRUE") # TRUE as.logical("FALSE") # FALSE # To factor as.factor(c("a", "b", "a")) # a b a # Levels: a b ``` ### Automatic Conversion ```r # R automatically converts during operations c(1, "hello", TRUE) # "1" "hello" "TRUE" (all character) 1 + "2" # 3 (character to numeric) ``` ## Summary - Variables created with `<-` assignment - Atomic types: numeric, character, logical, special (NULL, NA, NaN, Inf) - Vectors are 1-dimensional, created with `c()` - Matrices are 2-dimensional with `matrix()` - Lists can hold mixed types, accessed with `$` or `[[]]` - Dataframes are tabular, like spreadsheets - Use `as.*()` functions for type conversion - R uses 1-based indexing

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →