Character strings

Install required packages

DescTools

Create strings from existing objects

[1] "-2.8, -0.33, 0.43, 1.3, -1.25"
[1] "1.0000" "2.3450"

Create new strings and control their output

Create and format strings

[1] 1
[1] 6
[1] 1 2 3
[1] "group_A" "group_B" "group_C" "group_D" "group_E"
[1] "1: black"  "2: red"    "3: green3" "4: blue"   "5: cyan"  
[1] "1.a 2.b 3.c 4.d 5.e"

Beware of the way NA and NULL are treated in paste().

[1] "1_NA_2__3_"
[1] "For 20 particpants in group A, the mean was 14.200000"
[1] "1.235"

String output with cat() and print()

A string+with
+4+
words
[1] A string
[1] A string

Manipulate strings

[1] "a"   "bc"  "def"
[1] "GHI" "JK"  "I"  
AfairlyLongString 
         "AfrlLS" 
[1] "meroL" "muspi" "rolod" "tis"  
[1] "DE" "JK" "O"  ""  
[[1]]
[1] "abc" "def" "ghi"

[[2]]
[1] "jkl" "mno"
[[1]]
[1] "X" "y" "l" "o" "p" "h" "o" "n"

Find substrings

Basic pattern matching

[1]  2  3 NA NA
[1]  2  3  4 NA

Create and use regular expressions

See ?regex

[1] 1 3
[1]  TRUE FALSE  TRUE FALSE
[1]  4  1 -1
attr(,"match.length")
[1]  4  3 -1
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
[1] "DEFG" "ABC" 

Create regular expression from wildcards (globbing)

[1] "^asdf.*\\.txt$"

Replace substrings

[1] "ABC..F" "GHIxx"  "LMN+"   "PQR"   
[1] "LorXX ipsum dolor sit Lorem ipsum"
[1] "LorXX ipsum dolor sit LorXX ipsum"
[1] "412"

Evaluate strings as instructions

[1] 7
[1] 1 4 9

Useful packages

Package stringr provides more functions for efficiently and consistently handling character strings.

Detach (automatically) loaded packages (if possible)

Get the article source from GitHub

R markdown - markdown - R code - all posts