Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read txt file and replace word in R?

Tags:

r

In file a.txt containing "abc", I want to replace "abc" with "ccccccccccccccccccccc", How to read and replace in R? Thank you!

a.txt contents:

{\rtf1
{\fonttbl{\f1\fmodern\fcharset134;}}
{\info}
\sectd\pgwsxn11907\pghsxn16840\marglsxn1418\margrsxn1418
\margtsxn1440\margbsxn1440\sectdefaultcl
\headery851{\header\pard\qr\fs18\par}
\footery992{\footer\pard\qc\f0\fs18\chpgn\par}
\pard\qc\sb30\sa30\fs21 \par
\trowd\trautofit1\trgaph0\trleft-75\intbl\trqc           
\clbrdrt\brdrs\brdrw30\clbrdrb\brdrs\brdrw10\clvertalc\cellx6993\clbrdrt
\brdrs\brdrw30\clbrdrb\brdrs\brdrw10\clvertalc\cellx13986\clbrdrt\brdrs\brdrw30
\clbrdrb\brdrs\brdrw10\clvertalc\cellx20979
\qc\fs21 x\cell\qc\fs21 y\cell\qc\fs21 z\cell\row
\trowd\trautofit1\trgaph0\trleft-75\trqc                  
\clvertalc\cellx6993\clvertalc\cellx13986
\clvertalc\cellx20979
\qc\fs21 a\cell\qc\fs21 b\cell\qc\fs21 abc\cell\row
\trowd\trautofit1\trgaph0\trleft-75\intbl\trqc   
\clbrdrb\brdrs\brdrw30\clvertalc\cellx6993\clbrdrb\brdrs\brdrw30
\clvertalc\cellx13986\clbrdrb\brdrs\brdrw30\clvertalc\cellx20979
\qc\fs21 d\cell\qc\fs21 e\cell\qc\fs21 f\cell\row
}    
like image 684
stata Avatar asked May 05 '14 14:05

stata


People also ask

How do I replace a word in a string in R?

The sub() function in R is used to replace the string in a vector or a data frame with the input or the specified string.

Can R read TXT files?

R can read data from a variety of file formats—for example, files created as text, or in Excel, SPSS or Stata. We will mainly be reading files in text format . txt or . csv (comma-separated, usually created in Excel).

How do I read a text file line by line in R?

Read Lines from a File in R Programming – readLines() Function. readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines.


2 Answers

It's easy :

  • load your text in R using readLines (or scan)
  • change your pattern using sub or gsub
  • export your text to a text file using writeLines or scan

Example:

tx  <- readLines("~/Desktop/text.txt")
tx2  <- gsub(pattern = "abc", replace = "ccccccccccccccccccccc", x = tx)
writeLines(tx2, con="~/Desktop/text2.txt")

See R Programming wikibooks if you want to know more

like image 114
PAC Avatar answered Sep 21 '22 13:09

PAC


Original @PAC's variant but without creating variables. It uses the R-base native pipe (R 4.1.0) and the stringr package (a part of the tidyverse).

readLines("~/Desktop/text.txt") |>
  stringr::str_replace(
    pattern = "abc", 
    replace = "ccccccccccccccccccccc") |>
  writeLines(con = "~/Desktop/text2.txt")
like image 41
malexan Avatar answered Sep 23 '22 13:09

malexan