2

I would like to extract partial string from a list. I don't know how to define the pattern of the strings. Thank you for your helps.

library(stringr)
names = c("GAPIT..flowerdate.GWAS.Results.csv","GAPIT..flwrcolor.GWAS.Results.csv",
"GAPIT..height.GWAS.Results.csv","GAPIT..matdate.GWAS.Results.csv")
# I want to extract out "flowerdate", "flwrcolor", "height" and "matdate"
traits <- str_extract_all(string = files, pattern = "..*.")
# the result is not what I want.
1
  • . is a regex metacharacter. Commented Apr 26, 2014 at 3:01

4 Answers 4

4

You can also use regmatches

> regmatches(c, regexpr("[[:lower:]]+", c))
[1] "flowerdate" "flwrcolor"  "height"     "matdate"   

I encourage you not to use c as a variable name, because you're overwriting c function.

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

Comments

2

I borrow the answer from Roman Luštrik for my previous question “How to extract out a partial name as new column name in a data frame”

traits <- unlist(lapply(strsplit(names, "\\."), "[[", 3))

1 Comment

You can get rid of unlist by using sapply(strsplit(string, "\\."), "[[", 3)
2

Use sub:

sub(".*\\.{2}(.+?)\\..*", "\\1", names)
# [1] "flowerdate" "flwrcolor"  "height"     "matdate"   

Comments

1

Here are a few solutions. The first two do not use regular expressions at all. The lsat one uses a single gsub:

1) read.table. This assumes the desired string is always the 3rd field:

read.table(text = names, sep = ".", as.is = TRUE)[[3]]

2) strsplit This assumes the desired string has more than 3 characters and is lower case:

sapply(strsplit(names, "[.]"), Filter, f = function(x) nchar(x) > 3 & tolower(x) == x)

3) gsub This assumes that two dots preceed the string and one dot plus junk not containing two successive dots comes afterwards:

gsub(".*[.]{2}|[.].*", "", names)

REVISED Added additional solutions.

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.