【问题标题】:Does not work changing a value from dataframe in R无法从 R 中的数据框中更改值
【发布时间】:2016-02-15 07:44:53
【问题描述】:

我对 R 和网络抓取世界有点陌生。我真的不明白为什么df[df == "x"] 在这种情况下不起作用:

library(rvest)
library(dplyr)
library(tidyr)

# Step 1: Read URL
htmlpage <- read_html("http://www.bmbets.com/football/england/premier-league/")

# Step 2: Extract info from web
Data <- htmlpage %>%
  html_nodes("table") %>%
  html_table()

#Step 3: Subset correct table
Data <- Data[[3]]

# Step 4: Change column names
colnames(Data) <- c("Date", "Venue", "V1", "V2", "V3", "Payout", "B")

# Step 5: Select columns
Data <- select(Data, 1:5)

# Step 6: Separate 'Venue' column with tidyr package
Data <- Data %>%
  separate(Venue, into = c("Home", "Away"), sep = "\\-", extra = "merge")

# Step 7: Change team name
Data[Data == "Leicester City"] <- "Leicester"

tbl_df(Data)

结果如下:

                        Date               Home            Away    V1    V2    V3
                       (chr)              (chr)           (chr) (dbl) (chr) (dbl)
1                      12:45   West Ham United       Sunderland  1.81  3.61  4.41
2                      15:00    Leicester City     Norwich City  1.49  4.27  6.60
3                      15:00       Southampton          Chelsea  2.59  3.21  2.77

“莱斯特城”队不变!为什么?

'Data' 对象是一个 data.frame,Home 和 Away 字段是 'chr'...我认为问题与 tidyr 包有关,但即使我只是尝试在步骤 3 中更改团队名称不工作!

有什么想法吗?

【问题讨论】:

  • 因为它是"Leicester City ",而不是"Leicester City"。您可以通过Data[2,2] 轻松查看。
  • 在替换之前,我建议修剪字符串。在separate 部分之后,Data[,2:3]&lt;-lapply(Data[,2:3],trimws) 将删除所有前导/尾随空格。

标签: r web-scraping


【解决方案1】:

正如 cmets 中所指出的,问题是由于前导和尾随空格造成的。 @Pascal 和 @nicola 的 cmets 也提供了很好的解决方案。

如果这些空白字符不打扰您,并且您只是想在数据框中将“Leicester City”替换为“Leicester”,另一种方法是使用sub()gsub(),而不是搜索确切的身份.一种这样的可能性是:

Data[] <- sapply(Data, function(x) sub("Leicester City", "Leicester", x))
#> head(Data)
#   Date             Home            Away   V1   V2   V3
#1 12:45 West Ham United       Sunderland 1.81 3.61 4.41
#2 15:00       Leicester     Norwich City 1.49 4.27 6.61
#3 15:00     Southampton          Chelsea  2.6 3.21 2.77
#4 15:00      Stoke City      Aston Villa 1.64 3.63 5.78
#5 15:00         Watford      Bournemouth 2.35 3.28 3.04
#6 17:30   West Bromwich   Crystal Palace 2.58 3.12 2.86

【讨论】:

    【解决方案2】:

    跟随 Pascal 和 nicola 的 cmets,

    Data[,c("Home", "Away")] <- sapply(Data[,c("Home", "Away")],trimws)
    Data[Data == "Leicester City"] <- "Leicester"
    tbl_df(Data)
    

    【讨论】:

    • 我猜这个问题比这个“简单”的替换更广泛。
    • 谢谢。我错过了一个“]”
    猜你喜欢
    • 2021-01-15
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2018-01-01
    • 2019-03-30
    • 1970-01-01
    相关资源
    最近更新 更多