0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rでテキストを編集する

Last updated at Posted at 2025-11-13

テキストファイルの情報をR上で編集する方法についての備忘録です。

テキストファイルの読み込み

df <- read.table(file   ## ファイルパス
, header = FALSE        ## 列名の有無
, sep = ","             ## 区切り文字
, skip = 0              ## データ上部のコメントなど読み込み不要な行数を指定
)

返り値はデータフレームなので、行と列に分けられている状態である

文字列置換用の関数

stringr パッケージに含まれている str_replase 関数を使用する

str_replace(対象の列名, "検索文字列", "置換文字列")        ## 最初だけ置換
str_replace_all(対象の列名, "検索文字列", "置換文字列")    ## 全部置換

任意の文字を表したい場合は . を使用して表現する
任意の文字列を表したい場合は .*? を使用して表現する

「.」 任意の1文字

「*」 0文字以上 繰り返し

「?」 最短でマッチ


image.png

文字列をつなげる

all_text <- paste(texts             ## 対象
, collapse = ""                     ## 要素の間に挟む文字
)

何も挟まなくてよい場合は collapse に "" を指定する

区切り文字を指定して文字列を分割する(リスト化)

reviews <- strsplit(all_text         ## 対象
, "#####"                            ## 区切り文字
)

strsplit の返り値はリストである。対象にベクトルを指定できる。以下のような出力になる。

all_text <- c("あいう#####えお", "かきく#####けこ")
reviews <- strsplit(all_text, "#####")
reviews
[[1]]
[1] "あいう" "えお"

[[2]]
[1] "かきく" "けこ"

すなわち返り値 reviews について、reviews[1] はリストであることに注意
image.png

文字列前後の空白を削除する

str_trim() は文字列前後の空白のみを削除する。前後のスペース、タブ、改行などが対象で、文字列の途中にある空白は削除されない。

Rなので文字列ベクトルも対象に取れる。

texts <- str_trim(texts)    ## 対象

空行をNAにする

tests[texts == ""] <- NA
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?