English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

R 文字列

R言語の文字列は、シングルクォート「' '」またはダブルクォート「" "」で表されます。

  • シングルクォート文字列にはダブルクォートが含まれます。

  • シングルクォート文字列にはシングルクォートは含まれません。

  • ダブルクォート文字列にはシングルクォートが含まれます。

  • ダブルクォート文字列にはダブルクォートは含まれません。

以下の例では、文字列の使用を示します:

a <- 'シングルクォートを使用する'
print(a)
b <- 「ダブルクォートを使用する」
print(b)
c <- 「ダブルクォート文字列にはシングルクォート(')が含まれることができます
print(c)
d <- '単引号文字列の中にダブル引号(")が含まれることができます '
print(d)

以下のコードを実行すると、出力結果が:

[1] "単引号を使用する"
[1] "ダブル引号を使用する"
[1] "ダブル引号文字列の中に単引号(')が含まれることができます "
[1] "単引号文字列の中にダブル引号(\")が含まれることができます "

文字列操作

以下では R 言語のいくつかの内蔵関数が文字列に対する操作について見てみましょう。

paste() 関数

paste() 関数は指定された接続符を使用して文字列を結合するために使用されます、デフォルトの接続符は空格です。

文法形式:

paste(..., sep = " ", collapse = NULL)

パラメータ説明:

  • ... : 文字列リスト

  • sep : 分隔符、デフォルトは空格

  • collapse : 2つまたはそれ以上の文字列オブジェクトが要素の対応関係に基づいて結合され、文字列が結合された後に collapse で指定された接続符を使用して接続されます

a <- "Google"
b <- 'w3codebox'
c <- "Taobao"
print(paste(a,b,c))
print(paste(a,b,c, sep = ""))-"))
print(paste(letters[1:6],1:6, sep = "", collapse = "="))
paste(letters[1:6],1:6, collapse = ".")

以下のコードを実行すると、出力結果が:

[1] "Google w3codebox Taobao"
[1] "Google-w3codebox-Taobao"
[1] "a1=b2=c3=d4=e5=f6"
[1] "a 1.b 2.c 3.d 4.e 5.f 6"

format() 関数

format() 関数は文字列をフォーマットするために使用され、format() は文字列や数字に適用できます。

文法形式:

format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none"))

パラメータ説明:

  • x : 向量にinput

  • digits : 表示する桁数

  • nsmall : 小数点の右側に表示する最少の桁数

  • scientific : 設定科学計数法

  • width : 使用開頭填充空白來表示最小的宽度

  • justify:設定位置,表示可以是左側、右側、中央等。

# 表示 9 位,最後一位四捨五入
result <- format(23.123456789, digits = 9)
print(result)
# 使用科学计数法显示
result <- format(c(6, 13.14521), scientific = TRUE)
print(result)
# 小数点以下の最小表示 5 桁、ない場合は 0 で補完
result <- format(23.47, nsmall = 5)
print(result)
# 数字を文字列に変換
result <- format(6)
print(result)
# 幅 6 桁、不足している場合は先頭にスペースを追加
result <- format(13.7, width = 6)
print(result)
# 左寄せ
result <- format("w3codebox", width = 9, justify = "l")
print(result)
# 中央に表示
result <- format("w3codebox", width = 10, justify = "c")
print(result)

以下のコードを実行すると、出力結果が:

[1] "23.1234568"
[1] "6.000000e+00" "1.314521e+01"
[1] "23.47000"
[1] "6"
[1] "  13.7"
[1] "w3codebox   "
[1] "  w3codebox  "

nchar() 関数

nchar() 関数は文字列や数字リストの長さを計算します。

文法形式:

nchar(x)

パラメータ説明:

  • x : ベクターや文字列

result <- nchar("Google w3codebox Taobao"
print(result)

以下のコードを実行すると、出力結果が:

[1] 20

toupper() & tolower() 関数

toupper() & tolower() 関数は文字列の文字を大文字または小文字に変換します。

文法形式:

toupper(x)
tolower(x)

パラメータ説明:

  • x : ベクターや文字列

# 大文字に変換

result <- toupper("w3codebox")
print(result)
# 小文字に変換
result <- tolower("w3codebox")
print(result)

以下のコードを実行すると、出力結果が:

[1] "w3codebox"
[1] "w3codebox"

substring() 関数

substring() 関数は文字列を切り取るために使用されます。

文法形式:

substring(x,first,last)

パラメータ説明:

  • x : ベクターや文字列

  • first : 結果の始めの位置

  • last: 結果の終わりまでの位置

# から第 2 位から第 5 位
result <- substring("w3codebox", 2, 5)
print(result)

以下のコードを実行すると、出力結果が:

[1] "hooo"