0% found this document useful (0 votes)
21 views3 pages

Strings in Vector

Uploaded by

ca235213253
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views3 pages

Strings in Vector

Uploaded by

ca235213253
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Vector String Operations

# Create a vector of strings

fruits <- c("apple", "banana", "cherry", "date")

print(fruits)

# Access elements by index

fruits <- c("apple", "banana", "cherry", "date")

print(fruits[1])

print(fruits[2:3])

# Replace the second element

fruits <- c("apple", "banana", "cherry", "date")

fruits[2] <- "blueberry"

print(fruits)

# Add a new fruit to the vector

fruits <- c("apple", "banana", "cherry")

fruits <- c(fruits, "date")

print(fruits)

# Remove the third element

fruits <- c("apple", "banana", "cherry", "date")

fruits <- fruits[-3]

print(fruits)
# Sort the vector alphabetically

fruits <- c("banana", "apple", "date", "cherry")

sorted_fruits <- sort(fruits)

print(sorted_fruits)

# Get the length of the vector

fruits <- c("apple", "banana", "cherry", "date")

length_of_fruits <- length(fruits)

print(length_of_fruits)

# Combine strings in a vector

fruits <- c("apple", "banana", "cherry")

fruit_sentence <- paste(fruits, collapse = ", ")

print(fruit_sentence)

# Find elements containing the letter 'a'

fruits <- c("apple", "banana", "cherry", "date")

fruits_with_a <- fruits[grep("a", fruits)]

print(fruits_with_a)

# Convert strings to uppercase and lowercase

fruits <- c("apple", "banana", "cherry", "date")

uppercase_fruits <- toupper(fruits)

lowercase_fruits <- tolower(fruits)


print(uppercase_fruits)

print(lowercase_fruits)

# Find the number of characters in each string

fruits <- c("apple", "banana", "cherry", "date")

string_lengths <- nchar(fruits)

print(string_lengths)

# Replace part of a string

fruits <- c("apple", "banana", "cherry", "date")

new_fruits <- gsub("a", "@", fruits)

print(new_fruits)

# Split each string into individual characters

fruits <- c("apple", "banana")

split_fruits <- strsplit(fruits, "")

print(split_fruits)

# Check which elements match a pattern

fruits <- c("apple", "banana", "cherry", "date")

matches <- grepl("ch", fruits)

print(matches)

You might also like