Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The answer already given using <code>stringr</code> is excellent. That package provides you with some very helpful string munging tools. </p> <p>If you want to only use base, you could do this with <code>gsub</code>. Assuming your punctuation stays the same and there will not be any embedded periods or underscores in the X, Y or Z something like this should work</p> <pre><code>f &lt;- 'X_Y.doc.Z.x_y_z' gsub('^.+_(.+)\\.doc\\.(.+)\\..+_.+$', '\\1 \\2', f) </code></pre> <p>which returns:</p> <pre><code>"Y Z" </code></pre> <p>you could put whatever you want in there though to make it easier to get at each piece or could do this in two lines returning one each. And remember, R almost never changes data in place. You need to assign the output of a function to a variable like below. Otherwise it will just print to the console and be "lost" (this is true <em>most</em> of the time).</p> <pre><code>y &lt;- gsub('^.+_(.+)\\.doc\\..+\\..+_.+$', '\\1', f) z &lt;- gsub('^.+_.+\\.doc\\.(.+)\\..+_.+$', '\\1', f) </code></pre> <p>Lets break it down.</p> <p><code>^</code> specifies the beginning of a line. its good to be explicit. similarly <code>$</code> identifies the end of a line.</p> <p><code>.</code> represents any character and following it with a <code>+</code> means one or more of any character. If you used <code>.*</code> instead of <code>.+</code> it would mean zero or more of any character and that isnt what we want. If i want to write a normal <code>.</code> I need to escape it since its a special character. <code>\</code> is the escape character both for regular expressions and for R. So... you need two. To write a normal period you need to write <code>\\.</code></p> <p>Clear to be sure. Finally the parentheses represent a group I want to save. They can be referenced later using numbers indicating the order you saved them. In some languages these parentheses need to be escaped also, but not R.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload