【问题标题】:Split Character String at Underscore Using scan() Function in R - strsplit() vs. scan() Comparison使用 R 中的 scan() 函数在下划线处拆分字符串 - strsplit() 与 scan() 比较
【发布时间】:2022-01-06 08:24:45
【问题描述】:

我注意到函数 strsplit() 和 scan() 处理下划线的方式不同,我想知道为什么会这样。

请考虑以下示例代码:

x1 <- "string split"

strsplit(x1, " ")[[1]]
# [1] "string" "split" 

scan(text = x1, what = " ")
# [1] "string" "split" 

strsplit 和 scan 使用 " " 作为分隔符的输出是一样的。

但是,当我使用“_”作为分隔符时,输出是不同的:

x2 <- "string_split"

strsplit(x2, "_")[[1]]
# [1] "string" "split" 

scan(text = x2, what = "_")
# [1] "string_split"

为什么使用下划线作为分隔符时strsplit和scan的输出不同?

【问题讨论】:

  • what 不是分隔符,而应该是文本的类。

标签: r string function character


【解决方案1】:

参数what 不是分隔符,而是数据类型。在你的情况下,你有性格:

scan(text=x2, what = character(), sep='_', quiet = TRUE)
[1] "string" "split" 

【讨论】:

  • 非常感谢您的快速回复!你能解释一下为什么 scan() 在第一个例子中使用 what = " " 时会拆分字符串吗?
  • @JoachimSchork 因为可以采用参数中元素的类型。在这种情况下,typeof(' ') 是字符
  • @JoachimSchork 你可以试试scan(text = '1 2 3', what = 'numeric'),它会返回一个字符向量而不是数字。而scan(text = '1 2 3', what = 2) 将返回数字。希望这会有所帮助
  • 感谢您的额外解释!
猜你喜欢
  • 1970-01-01
  • 2013-03-04
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多