R nchar() 関数 - 文字数を取得
R nchar() 関数は文字列内の文字数を計算するために使用されます。
nchar() は中国語などのマルチバイト文字を処理でき、文字列処理の中で最も基本的な関数の一つです。
nchar() 関数の構文は次のとおりです:
nchar(x, type = "chars")
引数の説明:
x入力文字列ベクトル。
typeカウントタイプ:"chars"(文字数)、"bytes"(バイト数)、"width"(表示幅)。
実例
# 英語と中国語
text_en <- "Hello サンプル"
text_cn <- "你好世界"
print(paste("英語:", nchar(text_en)))
print(paste("中国語:", nchar(text_cn)))
# ベクトル内の文字数
words <- c("R", "Python", "JavaScript", "Go")
print("各言語の文字数:")
print(nchar(words))
# バイト数と文字数の違いを確認
text <- "Hello 世界"
print(paste("文字数:", nchar(text, type = "chars")))
print(paste("バイト数:", nchar(text, type = "bytes")))
text_en <- "Hello サンプル"
text_cn <- "你好世界"
print(paste("英語:", nchar(text_en)))
print(paste("中国語:", nchar(text_cn)))
# ベクトル内の文字数
words <- c("R", "Python", "JavaScript", "Go")
print("各言語の文字数:")
print(nchar(words))
# バイト数と文字数の違いを確認
text <- "Hello 世界"
print(paste("文字数:", nchar(text, type = "chars")))
print(paste("バイト数:", nchar(text, type = "bytes")))
上記のコードを実行すると、出力結果は次のとおりです:
[1] "英文: 12" [1] "中文: 4" [1] "各语言的字符数:" [1] 1 6 10 2 [1] "字符数: 8" [1] "字节数: 13"
nchar() と substr() を組み合わせると、文字列の切り詰めができます:
実例
# 長すぎる文字列を切り詰めて省略記号を追加
texts <- c(これは非常に長い説明文のため切り詰める必要がある,
"短文本")
truncate <- function(x, max_len = 10) {
ifelse(nchar(x) > max_len,
paste0(substr(x, 1, max_len), "..."),
x)
}
print("切り詰め結果:")
print(truncate(texts, max_len = 8))
texts <- c(これは非常に長い説明文のため切り詰める必要がある,
"短文本")
truncate <- function(x, max_len = 10) {
ifelse(nchar(x) > max_len,
paste0(substr(x, 1, max_len), "..."),
x)
}
print("切り詰め結果:")
print(truncate(texts, max_len = 8))
上記のコードを実行すると、出力結果は次のとおりです:
[1] "截断结果:" [1] "这是一个很长的描..." "短文本"その他の拡張
R言語の実例