将空格添加到单词列表中

cot*_*inR 0 r

我有一个像这样的单词/表达列表:

df = data.frame(word = c('word','my word', 'another+word-'))
Run Code Online (Sandbox Code Playgroud)

如何在单词/短语的开头和结尾后添加特定字符?

预期结果示例:

df = data.frame(word = c(' word ',' my word ', ' another+word- '))
Run Code Online (Sandbox Code Playgroud)

Sot*_*tos 8

这样做的方法很多.收集所有评论:

#Sotos
paste0(' ', df$word, ' ')

#Andre Elrico 1
sub("(.*)"," \\1 ",df$word)
#Andre Elrico 2
suppressMessages(paste(message("very easy question"), df$word, message("very easy question")))

#Cath 1
paste(NULL, df$word, NULL)
#Cath 2
sprintf(" %s ", df$word)
Run Code Online (Sandbox Code Playgroud)

使用stringr:

stringr::str_pad(df$word, width = nchar(df$word) + 2, side = "both")
Run Code Online (Sandbox Code Playgroud)

基准

library(microbenchmark)
library(stringr)

word <- sapply(sample(3:15, 1e6, replace=TRUE), function(nbchar) paste(sample(letters, nbchar, replace=TRUE), collapse=""))

Sotos <- function(word) paste0(' ', word, ' ')
Andre1 <- function(word) sub("(.*)"," \\1 ", word)
Andre2 <- function(word) suppressMessages(paste(message("very easy question"), word, message("very easy question")))
Cath1 <- function(word) paste(NULL, word, NULL)
Cath2 <- function(word) sprintf(" %s ", word)
strpad <- function(word) str_pad(word, width = nchar(word) + 2, side = "both")

microbenchmark(Sotos(word), Andre1(word), Andre2(word), Cath1(word), Cath2(word), strpad(word), unit="relative")

#         expr       min       lq     mean   median       uq       max neval   cld
#  Sotos(word) 1.2071789 1.190558 1.228668 1.190450 1.245905 1.0740482   100  b   
# Andre1(word) 2.9069459 2.731446 2.690268 2.711295 2.709019 2.1535507   100    d 
# Andre2(word) 0.9999499 1.002723 1.020524 1.000145 1.013569 0.7941186   100 a    
#  Cath1(word) 1.0000000 1.000000 1.000000 1.000000 1.000000 1.0000000   100 a    
#  Cath2(word) 1.4430192 1.403617 1.387463 1.402438 1.400566 1.1396474   100   c  
# strpad(word) 2.7101283 2.599947 2.789208 2.902455 2.942781 2.0281154   100     e
Run Code Online (Sandbox Code Playgroud)