[英]Does not work changing a value from dataframe in R
我对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中更改团队名称,它也不起作用!
有任何想法吗?
正如评论中指出的那样,问题是由于前导空格和尾随空格。 @Pascal和@nicola的评论也提供了一个很好的解决方案。
如果这些空白字符不打扰你,如果你只想在数据框中用“莱斯特”替换“莱斯特城”,则另一种方法是使用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
根据Pascal和nicola的评论,
Data[,c("Home", "Away")] <- sapply(Data[,c("Home", "Away")],trimws)
Data[Data == "Leicester City"] <- "Leicester"
tbl_df(Data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.