sub: Extract and replace subsequences from a bstr sequences

Description Usage Arguments Examples

Description

Extract and replace subsequences from a bstr sequences

Usage

1
2
3
4
5
bstr_sub(bstrobj, start = 1L, end = -1L)

bstr_sub(bstrobj, start = 1L, end = -1L, omit_na = FALSE) <- value

bstr_sub_replace(..., replacement, value = replacement)

Arguments

bstrobj

bstr class object or character vector

start

start

end

end

omit_na

Single logical value. If 'TRUE', missing values in any of the arguments provided will result in an unchanged input.

value

replacement string

...

arguments to be passed to bstr_sub<-

replacement

alias of value [wherever applicable]

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
temp <- bstr_rand_seq(1, 10, seed = 1)
c(
  temp,
  bstr_sub(temp, 1, 5),
  bstr_sub(temp, 5),
  bstr_sub(temp, end = 5),
  bstr_sub(temp, 1:2, c(6,2))
)

# Negative indices
c(
  temp,
  bstr_sub(temp, -1),
  bstr_sub(temp, -7),
  bstr_sub(temp, end = -7)
)

# Alternatively, you can pass in a two colum matrix, as in the
# output from bstr_locate
temp <- bstr("abcde fghij")
pos <- bstr_locate(temp, "[aefi]")[[1]]
bstr_sub(temp, pos)

# Vectorisation
bstr_sub(temp, seq_len(bstr_length(temp)))
bstr_sub(temp, end = seq_len(bstr_length(temp)))

# Replacement form
x <- "BBCDEF"
bstr_sub(x, 1, 1) <- "A"; x
bstr_sub(x, -1, -1) <- "K"; x
bstr_sub(x, -2, -2) <- "GHIJ"; x
bstr_sub(x, 2, -2) <- ""; x

# If you want to keep the original if some argument is NA,
# use omit_na = TRUE
x1 <- x2 <- x3 <- x4 <- bstr("AAA")
bstr_sub(x1, 1, NA) <- "B"
bstr_sub(x2, 1, 2) <- NA
bstr_sub(x3, 1, NA, omit_na = TRUE) <- "B"
bstr_sub(x4, 1, 2, omit_na = TRUE) <- NA
c(x1, x2, x3, x4)

t-arae/bstringr documentation built on March 18, 2021, 3:08 a.m.