【问题标题】:What is the meaning of " \\." in tidyr::separate?是什么意思 ” \\。”在 tidyr::separate 中?
【发布时间】:2020-01-30 08:37:51
【问题描述】:

“\.”的目的是什么,为什么要引用它? 这是代码:

library(tidyr)

iris.tidy <- iris %>%
  gather(key, Value, -Species) %>%
  separate(key, c("Part", "Measure"), "\\.")

用于鸢尾花数据集

【问题讨论】:

  • 您不需要 R 中 "\\." 的含义,而是特别需要 separate"\\." 的含义。阅读?separate
  • 相关帖子:stackoverflow.com/q/6638072/680068 我们需要转义转义字符。
  • 我不理解单独函数中的键这个词,因为我们使用管道,数据参数在函数之前,我们没有提到它作为第一个参数,所以我们的第一个参数使用seperate() 是col,即列名或位置,问题是整个鸢尾花数据集没有名为key 的列!
  • 列名key 来自gather 你在哪里gather(key, Value, -Species)

标签: r dplyr tidyr


【解决方案1】:

如果你一步一步运行代码会更容易理解。

gather 带来长格式数据,列 key 带有列名,列 value 带有这些列的值

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

然后我们使用separatekey 列根据其文本中的"." 分为两列。

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

由于separate 中的sep 参数接受正则表达式,而. 在正则表达式中具有特殊含义,如果我们要指定实际的.,我们需要对其进行转义,因此我们使用"\\."。另请注意,gather 在较新版本的tidyr 中已替换为pivot_longer

【讨论】:

  • 这正是我正在寻找的解释类型,非常感谢!
【解决方案2】:

. 表示每个字符(在正则表达式中)。如果您实际上不想将其作为"."(字符本身),则需要使用\“转义”它,但它也是正则表达式中的特殊字符,因此也需要转义。

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 2020-01-09
    • 2011-08-12
    • 2017-06-11
    • 2018-03-05
    • 2023-03-27
    • 2016-08-17
    • 2010-12-28
    • 2020-10-27
    相关资源
    最近更新 更多