What is the meaning of “ \\.” in tidyr::separate?

醉酒当歌 提交于 2020-02-16 08:16:58

问题


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


回答1:


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.




回答2:


. 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.



来源:https://stackoverflow.com/questions/59981881/what-is-the-meaning-of-in-tidyrseparate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!