I am writing an R script and want to define a variable to be used in plot annotations as part of the file name. I thought I would use the strsplit() function. Here is my code and the output:
infile = "ACC_1346.table.txt"
x = strsplit(infile, ".")
class(infile)
[1] "character"
class(x)
[1] "list"
str(x)
List of 1
$ : chr [1:18] "" "" "" "" ...
x[[1]]
[1] "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
I expected the final output to be:
[1] "ACC_1346" "table" "txt"
What is going on here?
To avoid regex altogether use fixed = TRUE
in the call of strsplit
infile = "ACC_1346.table.txt"
x = strsplit(infile, ".", fixed = TRUE)
x
[[1]]
[1] "ACC_1346" "table" "txt"
strsplit
seeks for a regex to do it's splitting. In regex a "." is a wildcard that pretty much matches anything. To actually match the dot you need to escape using \
. Since \
is also an escape character in R, you need to escape it twice as \\.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With