我想从列表中提取部分字符串。我不知道如何定义字符串的模式。谢谢你的帮助。
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.发布于 2014-04-26 15:16:15
以下是一些解决办法。前两个根本不使用正则表达式。lsat一号使用单个gsub。
1) read.table.这假设所需的字符串始终是第三个字段:
read.table(text = names, sep = ".", as.is = TRUE)[[3]]2) str拆分--这假定所需的字符串有3个以上的字符,大小写如下:
sapply(strsplit(names, "[.]"), Filter, f = function(x) nchar(x) > 3 & tolower(x) == x)3) gsub --假设字符串前面有两个点,然后是一个点加上不包含两个连续点的垃圾:
gsub(".*[.]{2}|[.].*", "", names)修订了,增加了更多的解决方案。
发布于 2014-04-26 03:22:36
您也可以使用regmatches
> regmatches(c, regexpr("[[:lower:]]+", c))
[1] "flowerdate" "flwrcolor" "height" "matdate" 我鼓励您不要使用c作为变量名,因为您正在覆盖c函数。
发布于 2014-04-26 03:13:17
在前面的问题中,我借用了Romanštrik的答案:“如何在数据框架中提取出作为新列名的部分名称”。
traits <- unlist(lapply(strsplit(names, "\\."), "[[", 3))https://stackoverflow.com/questions/23306073
复制相似问题