您将如何提取所有字符直到指定字符?例如,我想提取“。”之前的所有内容。(时期):
a<-c("asdasd.sss","segssddfge.sss","se.sss")
我想回来:
asdasd segssddfge se
我试过:
substr(a,1,".")
但它似乎不起作用。
有任何想法吗?
您将如何提取所有字符直到指定字符?例如,我想提取“。”之前的所有内容。(时期):
a<-c("asdasd.sss","segssddfge.sss","se.sss")
我想回来:
asdasd segssddfge se
我试过:
substr(a,1,".")
但它似乎不起作用。
有任何想法吗?
这是一个非常基本的方法:
sapply(strsplit(a, "\\."), `[[`, 1)
# [1] "asdasd" "segssddfge" "se"
还有一个:
sub(".sss", "", a, fixed = TRUE)
# [1] "asdasd" "segssddfge" "se"
## OR sub("(.*)\\..*", "\\1", a)
## And possibly other variations
使用sub
:
# match a "." (escape with "\" to search for "." as a normal "."
# means "any character") followed by 0 to any amount of characters
# until the end of the string and replace with nothing ("")
sub("\\..*$", "", a)
使用subtr
and gregexpr
(假设只有 1.
并且向量内的所有字符串都有明确的匹配)。
# get the match position of a "." for every string in "a" (returns a list)
# unlist it and get the substring of each from 1 to match.position - 1
substr(a, 1, unlist(gregexpr("\\.", a)) - 1)
这里尝试使用gsub
gsub(pattern='(.*)[.](.*)','\\1', c("asdasd.sss","segssddfge.sss","se.sss"))
[1] "asdasd" "segssddfge" "se"