# Sample string
my_string <- "Hello, world! How are you doing today? #excited"
# Function to count occurrences of a specific special symbol
count_symbol <- function(string, symbol) {
# Split the string into individual characters
characters <- unlist(strsplit(string, ""))
# Use grepl to find matches to the symbol and sum them up
sum(grepl(symbol, characters))
}
unlist(strsplit(my_string, ""))
## [1] "H" "e" "l" "l" "o" "," " " "w" "o" "r" "l" "d" "!" " " "H" "o" "w" " " "a"
## [20] "r" "e" " " "y" "o" "u" " " "d" "o" "i" "n" "g" " " "t" "o" "d" "a" "y" "?"
## [39] " " "#" "e" "x" "c" "i" "t" "e" "d"
# Count how many times '#' appears in my_string
count_hash <- count_symbol(my_string, "#")
print(count_hash)
## [1] 1
# Count how many times '?' appears in my_string
count_question <- count_symbol(my_string, "\\?")
print(count_question)
## [1] 1
############################################################
# Sample DataFrame
df <- data.frame(text_column = c("Hello, world!", "#This#is#an#example.", "NoSpecialSymbols123", "Special: #, $, and %"),
stringsAsFactors = FALSE) # Prevent automatic conversion to factor type
df
## text_column
## 1 Hello, world!
## 2 #This#is#an#example.
## 3 NoSpecialSymbols123
## 4 Special: #, $, and %
# Specify the symbol to count, for example "#"
symbol_to_count <- "#" # You can change this symbol as needed
# Apply the count_symbol function to each row of the 'text_column' and store the results in a new column
df$symbol_count <- sapply(df$text_column, count_symbol, symbol = symbol_to_count)
# View the results
print(df)
## text_column symbol_count
## 1 Hello, world! 0
## 2 #This#is#an#example. 4
## 3 NoSpecialSymbols123 0
## 4 Special: #, $, and % 1