我想编辑字符串的地址,例如这个例子:
test = c("[Mavlyanova, Nadira G.] Uzbek Acad Sci, GA Mavlyanov Inst Seismol, Tashkent 700135, Uzbekistan; [Markovic, Slobodan B.] Univ Novi Sad, Fac Sci, Chair Phys Geog, Novi Sad 21000, Serbia; [Rowell, G.] Univ Adelaide, Sch Chem & Phys, Adelaide, SA 5005, Australia; [Katarzynski, K.] Nicholas Copernicus Univ, Torun Ctr Astron, PL-87100 Torun, Poland; [Ansari, Z.; Boettcher, M.; Manschwetus, B.; Rottke, H.; Sandner, W.] Max Born Inst, D-12489 Berlin, Germany; [Milosevic, D. B.] Univ Sarajevo, Fac Sci, Sarajevo 71000, Bosnia & Herceg")
我只想得到国家名称。这是我到目前为止所尝试的:
> testa <- gsub("\\[.*?\\] ", "", test) #remove square brackets
> testa <- strsplit(testa, ";", fixed = TRUE) #split adresses
> testa <- sapply(testa, function(x) gsub("^.*, ([A-Za-z ]*)$", "\\1", x)) #keep only what's after last comma
> testa <- gsub("^ | $", "", testa) #remove spaces
> testa
[,1]
[1,] "Uzbekistan"
[2,] "Serbia"
[3,] "Australia"
[4,] "Poland"
[5,] "Germany"
[6,] "Univ Sarajevo, Fac Sci, Sarajevo 71000, Bosnia & Herceg"
因此,不幸的是,这不适用于最后一个地址。我想获得以下输出:
> testa
[,1]
[1,] "Uzbekistan"
[2,] "Serbia"
[3,] "Australia"
[4,] "Poland"
[5,] "Germany"
[6,] "Bosnia & Herceg"
我的问题是:
- 我的 sapply 函数中的错误是什么,导致它也无法正确使用最后一个地址?
- 如何改进它以实现正确的输出?