what is the purpose of " \. " and why it is quoted? this is the code:
library(tidyr)
iris.tidy <- iris %>%
gather(key, Value, -Species) %>%
separate(key, c("Part", "Measure"), "\\.")
it is for the iris dataset
what is the purpose of " \. " and why it is quoted? this is the code:
library(tidyr)
iris.tidy <- iris %>%
gather(key, Value, -Species) %>%
separate(key, c("Part", "Measure"), "\\.")
it is for the iris dataset
.
says every character (in a regular expression). If you actually wan't it as a "."
(the character itself) you need to "escape" it with a \
which however is a special character in regular expressions as well and therefore also needs to be escaped.
It would be easier to understand if you run the code step by step.
gather
brings the data in long format with column key
with column names and column value
with values of those columns
library(tidyr)
iris %>% gather(key, Value, -Species) %>% head
# Species key Value
#1 setosa Sepal.Length 5.1
#2 setosa Sepal.Length 4.9
#3 setosa Sepal.Length 4.7
#4 setosa Sepal.Length 4.6
#5 setosa Sepal.Length 5.0
#6 setosa Sepal.Length 5.4
We then use separate
to divide key
column in two columns based on "."
in their text.
iris %>%
gather(key, Value, -Species) %>%
separate(key, c("Part", "Measure"), "\\.") %>% head
# Species Part Measure Value
#1 setosa Sepal Length 5.1
#2 setosa Sepal Length 4.9
#3 setosa Sepal Length 4.7
#4 setosa Sepal Length 4.6
#5 setosa Sepal Length 5.0
#6 setosa Sepal Length 5.4
Since the sep
argument in separate
accepts regex and .
has a special meaning in regex, if we want to specify actual .
we need to escape it, hence we use "\\."
. Also note that gather
has been replaced with pivot_longer
in the newer version of tidyr
.