0

This is the name of a file that I have on R:

> lst.files[1]
[1] "clt_Amon_CanESM2_rcp45_185001-230012.nc"

What I need to do is capture just the part until the 4th underscore (including), so it would be something like this:

clt_Amon_CanESM2_rcp45_

How can I get this in R?

3 Answers 3

2

If you know you always have (at least) four underscores, then you could do something like this:

regmatches(lst, regexec(".*_.*_.*_.*_", lst.files[1]))[[1]]
# [1] "clt_Amon_CanESM2_rcp45_"

If potentially not always four, but no underscores in the second part, you could do something like this:

regmatches(lst, regexec(".*_", lst.files[1]))[[1]]
# [1] "clt_Amon_CanESM2_rcp45_"

This doesn't require any extra package, just base R.

Sign up to request clarification or add additional context in comments.

Comments

2

Using the qdap package, you can do the following.

x <- "clt_Amon_CanESM2_rcp45_185001-230012.nc"

library(qdap)
beg2char(x, "_", 4, include = TRUE)
# [1] "clt_Amon_CanESM2_rcp45_"

8 Comments

Great answer but I would prefer to stick to R's native commands. I am loading too many packages already and eventually I will get conflict between some commands :D
THe function is new for me. +1
@akrun I am glad that you found this useful. :)
@jazzurro I noted down this in my book to use it next time :-)
Wow, you completed >7000 review tasks, impressive!
|
2

We can also capture the repeating patterns as a group using sub. We match one more more characters from the beginning (^) of the string that is not an underscore ([^_]+) followed by an underscore (\\_) which is repeated 4 times ({4}), capture that as a group by wrapping with parentheses followed by zero or more characters (.*). We replace it with the capture group (\\1) to get the expected output.

sub('^(([^_]+\\_){4}).*', '\\1', str1)
#[1] "clt_Amon_CanESM2_rcp45_"

data

str1 <-  "clt_Amon_CanESM2_rcp45_185001-230012.nc"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.