【问题标题】:R: which() function can't find specified string in character vector (vector DOES contain string)R:which()函数在字符向量中找不到指定的字符串(向量包含字符串)
【发布时间】:2016-04-20 19:21:39
【问题描述】:

我编写了一个简单的函数来从 Baseball Reference.com 上抓取所有 MLB 投手的姓名。我创建了一个带有刮擦名称的向量,从原始刮擦名称中删除了 Â,并强制转换为字符向量。

library(rvest)
url <- "http://www.baseball-reference.com/leagues/MLB/2016-standard-pitching.shtml"
mlbpitcherdata <- read_html(url)

mlbpitchers <- mlbpitcherdata %>% html_nodes("td:nth-child(2) a") %>%  html_text()
mlbpitchers <- as.character(sapply(mlbpitchers, function(x) gsub("Â","",x))) # Remove "Â" from all raw pitcher names

然后我尝试在字符向量中查找特定名称的索引,我知道它在向量内部,which() 函数返回integer(0)

# Search for pitcher name in list of pitchers = Returns integer(0)!
which(mlbpitchers=="Chad Bettis")
integer(0)

# But, mlbpitchers CLEARLY has Chad Bettis inside of it.
mlbpitchers[26]
[1] "Chad Bettis"

我很困惑为什么which() 函数不能识别名称。我非常感谢任何人的帮助。我知道这可能是一件非常愚蠢和容易的事情,但我想不通!谢谢!

(注意:删除 Â 字符后,我被要求选择保存编码。我选择系统默认值:ISO 8859-1。我不确定这是否会导致问题。)

【问题讨论】:

  • rawToChar(charToRaw(mlbpitchers[26]),multiple = TRUE) 可能说明了问题,但我不是奇怪隐藏字符方面的专家。

标签: r vector character


【解决方案1】:

这是一个编码问题。特别是,如果您查看

R> substr(mlbpitchers[26], 1, 4) == "Chad"
[1] TRUE
R> substr(mlbpitchers[26], 5, 5) == " "
[1] FALSE

正如 Joran 建议的那样,使用

R> rawToChar(charToRaw(mlbpitchers[26]),multiple = TRUE)
[1] "C"    "h"    "a"    "d"    "\xc2" "\xa0" "B"    "e"    "t"    "t"   
[11] "i"    "s"   

也突出了这个问题。这些字符(感谢 Nicola)是 html non-breaking 空格。要删除它们,请使用

gsub("\xc2\xa0"," ",mlbpitchers)

【讨论】:

  • 这是我在调用您所说的内容时所观察到的:rawToChar(charToRaw(mlbpitchers[26]),multiple = TRUE) [1] "C" "h" "a" "d" " " "B" "e" "t" "t" "i" "s"
  • 这些是不间断空格:en.wikipedia.org/wiki/Non-breaking_space 删除它们:gsub("\xc2\xa0"," ",mlbpitchers)
  • @IRNotSmart 我不明白。比较第 5 个字符时会发生什么?
  • @csgillespie, @nicola substr(mlbpitchers[26], 5, 5) == " " [1] FALSE 很困惑,伙计。我不知道为什么我在调用 row 到 char 时没有看到 \xc2\xao
  • @IRNotSmart 两个想法:(1)重启R再试一次,(2)分享你在什么平台上。
猜你喜欢
  • 2012-06-13
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 2012-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多