一种选择是使用word
from stringr
withsep
参数
library(stringr)
word(string, 1, sep = ",")
#[1] "A" "B" "A"
word(string, 3, sep = ",")
#[1] "some text" "some other text" "yet another one"
由于 的性能word
是最差的,我发现了另一个在基础 R 中使用正则表达式的选项。
#Get 1st element
sub("(?:[^,],){0}([^,]*).*", "\\1",string)
#[1] "A" "B" "A"
#Get 3rd element
sub("(?:[^,],){2}([^,]*).*", "\\1",string)
#[1] "some text" "some other text" "yet another one"
这里有两组要匹配。第一个匹配任何不是逗号的字符,后跟一个逗号n
,然后再次匹配另一组不是逗号的字符。第一组未被捕获 ( ?:
),而第二组被捕获并返回。另请注意,括号 ( {}
) 中的数字必须比我们想要的单词少一。所以{0}
返回第一个单词并{2}
返回第三个单词。
基准
string <- c("A,1,some text,200","B,2,some other text,300","A,3,yet another one,100")
string <- rep(string, 1e5)
library(microbenchmark)
microbenchmark(
tmfmnk_sapply = sapply(strsplit(string, ","), function(x) x[1]),
tmfmnk_tstrsplit = tstrsplit(string, ",")[[1]],
avid_useR_sapply = sapply(strsplit(string, ","), '[', 1),
avid_useR_str_split = str_split(string, ",", simplify = TRUE)[,1],
Ronak_Shah_word = word(string, 1, sep = ","),
Ronak_Shah_sub = sub("(?:[^,],){0}([^,]*).*", "\\1",string),
G_Grothendieck ={DF <- read.table(text = string, sep = ",",as.is = TRUE);DF[[1]]},
times = 5
)
#Unit: milliseconds
# expr min lq mean median uq max neval
# tmfmnk_sapply 1629.69 1641.61 2128.14 1834.99 1893.43 3640.96 5
# tmfmnk_tstrsplit 1269.94 1283.79 1286.29 1286.68 1290.76 1300.30 5
# avid_useR_sapply 1445.40 1447.64 1555.76 1498.14 1609.52 1778.13 5
#avid_useR_str_split 324.68 332.28 332.30 333.97 334.01 336.54 5
# Ronak_Shah_word 6571.29 6810.92 6956.20 6930.86 7217.26 7250.69 5
# Ronak_Shah_sub 349.76 354.77 356.91 358.91 359.17 361.94 5
# G_Grothendieck 354.93 358.24 364.43 362.24 367.79 378.94 5
我没有包括 Christoph 的解决方案,因为我不清楚它如何适用于 variable n
。例如第 3 位,第 4 位等。