Introduction
Vectors are like lists that hold many items of the same type. Numeric vectors hold numbers, and character vectors hold words or letters.
Vectors are like lists that hold many items of the same type. Numeric vectors hold numbers, and character vectors hold words or letters.
numeric_vector <- c(1, 2, 3, 4) character_vector <- c("apple", "banana", "cherry")
The c() function combines values into a vector.
All items in a vector must be the same type: all numbers or all characters.
numbers and a character vector words.numbers <- c(10, 20, 30, 40) words <- c("cat", "dog", "bird")
mixed <- c(1, "two", 3)
empty_numeric <- numeric(5) empty_character <- character(3)
This program creates a numeric vector and a character vector, then prints both.
numeric_vector <- c(5, 10, 15) character_vector <- c("red", "green", "blue") print(numeric_vector) print(character_vector)
Vectors are the basic building blocks for data in R.
Use typeof() to check the type of a vector.
Mixing types in a vector causes automatic conversion to a common type.
Numeric vectors hold numbers, character vectors hold text.
Use c() to create vectors.
All elements in a vector must be the same type.
c(1, 2, 3, 4) has only numbers, so it is a numeric vector. c("one", "two", "three") has text, c(TRUE, FALSE, TRUE) has logical values, and c(1, "two", 3) mixes numbers and text, which converts all to characters.c("apple", "banana", "cherry") has all elements as quoted text strings, so it is a character vector. c(1, 2, 3) is numeric, c(TRUE, FALSE, TRUE) is logical, and c(1, "banana", 3) mixes types causing coercion.x <- c(5, 10, 15)
y <- c("a", "b", "c")
z <- c(x, y)
print(z)
vec <- c(1, 2, "three", 4)
sum(vec)
nums <- c(2, 4, 6, 8)
chars <- c("2", "4", "6", "8")
chars and add it to nums element-wise?Pass the test and this pattern moves unknown