【发布时间】:2017-10-03 02:13:48
【问题描述】:
我正在尝试创建一个函数,该函数能够返回同一字符串的不同版本,但字母之间有空格。
类似:
input <- "word"
返回:
w ord
wo rd
wor d
【问题讨论】:
我正在尝试创建一个函数,该函数能够返回同一字符串的不同版本,但字母之间有空格。
类似:
input <- "word"
返回:
w ord
wo rd
wor d
【问题讨论】:
我们首先使用strsplit 将字符串分解为每个字符。然后我们在每个位置使用sapply append 一个空白空间。
input <- "word"
input_break <- strsplit(input, "")[[1]]
c(input, sapply(seq(1,nchar(input)-1), function(x)
paste0(append(input_break, " ", x), collapse = "")))
#[1] "word" "w ord" "wo rd" "wor d"
?append 给我们append(x, values, after = length(x))
其中x 是向量,value 是要插入的值(此处为 " " ),after 是您要插入values 的位置。
【讨论】:
这是一个使用sub的选项
sapply(seq_len(nchar(input)-1), function(i) sub(paste0('^(.{', i, '})'), '\\1 ', input))
#[1] "w ord" "wo rd" "wor d"
或substring
paste(substring(input, 1, 1:3), substring(input, 2:4, 4))
#[1] "w ord" "wo rd" "wor d"
【讨论】: