基本的なstringr操作を習得したら、より高度なテキスト分析と自然言語処理に挑戦しましょう。
現代のデータ分析では、テキストデータからの洞察抽出が重要な競争優位となります。
📊 テキストデータの統計分析
# テキストの統計的分析
library(tidyverse)
library(tidytext)
library(stringr)
# テキストデータの統計的特徴量抽出
extract_text_features <- function(text_data) {
text_data %>%
mutate(
# 基本統計
char_count = str_length(text),
word_count = str_count(text, "\\S+"),
sentence_count = str_count(text, "[.!?]+"),
# 複雑性指標
avg_word_length = char_count / word_count,
avg_sentence_length = word_count / sentence_count,
# 読みやすさスコア(Flesch Reading Ease近似)
readability = 206.835 - (1.015 * avg_sentence_length) - (84.6 * avg_word_length),
# 感情分析指標
exclamation_ratio = str_count(text, "!") / sentence_count,
question_ratio = str_count(text, "\\?") / sentence_count,
# 大文字使用率
uppercase_ratio = str_count(text, "[A-Z]") / char_count,
# 数値含有率
digit_ratio = str_count(text, "\\d") / char_count
)
}
# N-gramとキーワード分析
analyze_text_patterns <- function(text_data, n = 2) {
text_data %>%
unnest_tokens(word, text) %>%
anti_join(stop_words) %>%
# N-gram生成
mutate(ngram = paste(word, lead(word, n-1), sep = " ")) %>%
count(ngram, sort = TRUE) %>%
head(20)
}
🧠 感情分析と意見マイニング
# 感情分析と意見マイニング
library(tidyverse)
library(tidytext)
library(textdata)
# 多次元感情分析
comprehensive_sentiment <- function(text_data) {
# AFINNレキシコン(-5から+5の感情スコア)
afinn_sentiment <- text_data %>%
unnest_tokens(word, text) %>%
inner_join(get_sentiments("afinn")) %>%
group_by(document_id) %>%
summarise(
afinn_score = sum(value),
afinn_mean = mean(value),
.groups = "drop"
)
# NRCレキシコン(感情カテゴリ)
nrc_emotions <- text_data %>%
unnest_tokens(word, text) %>%
inner_join(get_sentiments("nrc")) %>%
count(document_id, sentiment) %>%
pivot_wider(names_from = sentiment, values_from = n, values_fill = 0)
# 結果の統合
left_join(afinn_sentiment, nrc_emotions, by = "document_id")
}
# トピックモデリング準備
prepare_topic_modeling <- function(text_data) {
text_data %>%
unnest_tokens(word, text) %>%
anti_join(stop_words) %>%
filter(str_length(word) > 3) %>%
count(document_id, word) %>%
cast_dtm(document_id, word, n)
}
🔍 高度な正規表現パターン
# 実用的な高度な正規表現パターン
library(stringr)
# ビジネスデータ抽出パターン
business_patterns <- list(
# 日本の郵便番号(123-4567形式)
postal_code = "\\d{3}-\\d{4}",
# 電話番号(複数形式対応)
phone = "(\\d{2,4}[-\\s]?\\d{2,4}[-\\s]?\\d{4}|\\d{10,11})",
# メールアドレス
email = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}",
# URL(http/https)
url = "https?://[\\w\\.-]+(?:/[\\w\\.-]*)*(?:\\?[\\w&=%\\.-]*)?(?:#[\\w\\.-]*)?",
# 金額(円、カンマ区切り)
amount_yen = "¥?[0-9,]+円?",
# 日付(YYYY/MM/DD, YYYY-MM-DD形式)
date = "\\d{4}[/-]\\d{1,2}[/-]\\d{1,2}",
# IPアドレス
ip_address = "\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b"
)
# データクリーニング関数
clean_business_data <- function(text_vector) {
text_vector %>%
# 全角数字を半角に変換
str_replace_all("[0-9]", function(x) as.character(utf8ToInt(x) - utf8ToInt("0") + utf8ToInt("0"))) %>%
# 全角英字を半角に変換
str_replace_all("[A-Za-z]", function(x) intToUtf8(utf8ToInt(x) - utf8ToInt("A") + utf8ToInt("A"))) %>%
# 不要な空白を削除
str_trim() %>%
str_squish()
}
# エンティティ抽出関数
extract_entities <- function(text, pattern_name) {
pattern <- business_patterns[[pattern_name]]
str_extract_all(text, pattern) %>%
map(~ if(length(.x) > 0) .x else NA_character_)
}
🚀 テキストマイニングワークフロー
# 包括的なテキストマイニングワークフロー
library(tidyverse)
library(tidytext)
library(wordcloud)
# 統合テキスト分析パイプライン
text_mining_pipeline <- function(data, text_column) {
# Step 1: データクリーニング
cleaned_data <- data %>%
mutate(
text_clean = {{text_column}} %>%
str_to_lower() %>%
str_remove_all("[^\\w\\s]") %>%
str_squish()
)
# Step 2: トークン化と基本統計
tokens <- cleaned_data %>%
unnest_tokens(word, text_clean) %>%
anti_join(stop_words)
# Step 3: 頻度分析
word_freq <- tokens %>%
count(word, sort = TRUE) %>%
mutate(proportion = n / sum(n))
# Step 4: TF-IDF分析
tfidf <- tokens %>%
count(document_id, word) %>%
bind_tf_idf(word, document_id, n)
# Step 5: 感情分析
sentiment <- comprehensive_sentiment(cleaned_data)
list(
cleaned_data = cleaned_data,
word_freq = word_freq,
tfidf = tfidf,
sentiment = sentiment
)
}
💡 実践的アドバイス
🔍 テキスト分析の成功法則
- ドメイン知識を活用:業界特有の用語や表現を理解する
- データ品質を重視:ノイズの多いテキストは前処理が鍵
- 多角的なアプローチ:複数の手法を組み合わせて検証
- 可視化で洞察を深める:ワードクラウドやネットワーク図を活用
- 継続的な改善:結果をフィードバックして手法を改良
これらの高度なテキスト分析技法により、文書データから価値ある洞察を効率的に抽出できるようになります。
次の章では、カテゴリカルデータと関数型プログラミングの活用法を学びましょう。