如果你想找到你的向量的所有元素都在開始和刪除它們之前到底有共同的特點,你可以這樣做:
library(purrr)
## Replicating the data
v = c("nRsp ;A810SS-Q1D-01 \"","nRsp ;C5A19A60WESD04 \"","nRsp ;461961 \"")
## Split each string into a vector
l = strsplit(v,"")
## Find the common parts at the start and end of all elements in the list
start = 1
while(every(l,function(x) sum(x[1:start]==l[[1]][1:start])==start)){start=start+1}
end = 1
while(every(l,function(x) sum(rev(x)[1:end]==rev(l[[1]])[1:end])==end)){end=end+1}
## Remove the common 'garbage' from each element of the list
v2 = sapply(l,function(x) paste(x[start:(length(x)-end+1)],collapse=""))
這將返回:
[1] "A810SS-Q1D-01" "C5A19A60WESD04" "461961"
開始時它總是'nRsp;'? – hwnd
不,每次程序運行時它都會是一組不同的字符 –