Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character "|" in strsplit function (vertical bar / pipe)

Tags:

r

I was curious about:

> strsplit("ty,rr", split = ",")  
[[1]]
[1] "ty" "rr"

> strsplit("ty|rr", split = "|")
[[1]]
[1] "t" "y" "|" "r" "r"

Why don't I get c("ty","rr") from strsplit("ty|rr", split="|")?

like image 363
Dd Pp Avatar asked Aug 29 '12 15:08

Dd Pp


People also ask

What is the vertical bar character called?

The vertical bar ( | ) -- also called the vertical line, vertical slash, pipe, pipe symbol or upright slash -- is a symbol used in mathematics, computing and other areas to represent a specific type of logic or operation, depending on its context.

Which character is used for piping?

A pipe symbol is a typographical mark that resembles a vertical line ( | ). This mark is also known by many other names, such as a vertical bar or a vertical line.

What is vertical bar on keyboard?

How to Type the Vertical Line Character on a Keyboard. The pipe character is not hidden on a keyboard. It is located right above the Enter key. Another way to type the vertical bar character is to turn on the numeric keypad, hold ALT , then press 1, 2, and 4.

What is the vertical bar or pipe used for?

The vertical bar character (|), located over the backslash (\) key, is used as an OR operator. In the C/C++ language, two vertical bars are used; for example, if (x == 'a' || x == 'b') means "if X is equal to A or B." It is also used as a pipe symbol, which directs the output of one process to another.


1 Answers

It's because the split argument is interpreted as a regular expression, and | is a special character in a regex.

To get round this, you have two options:

Option 1: Escape the |, i.e. split = "\\|"

strsplit("ty|rr", split = "\\|")
[[1]]
[1] "ty" "rr"

Option 2: Specify fixed = TRUE:

strsplit("ty|rr", split = "|", fixed = TRUE)
[[1]]
[1] "ty" "rr"

Please also note the See Also section of ?strsplit, which tells you to read ?"regular expression" for details of the pattern specification.

like image 102
Andrie Avatar answered Oct 01 '22 06:10

Andrie