可以在这里找到可复制的代码:https://gist.github.com/jeffgswanson/703bb9eb1698518d1dd9aec43e91fefd
我想将其分为四栏:客场得分、客场球队、主场得分、主队。
我遇到的问题是我抓取的一些团队旁边也有一个排名,这就是你在括号中看到的。这给我带来了问题,因为我无法汇总团队名称,因为它们的拼写不一致。我尝试了无数种方法,要么一开始就避免刮掉括号中的内容,要么在事后删除它们,但都无济于事。
我最近的尝试是使用 gsub 来删除它们,但它也不起作用:
scores <- scores %>% mutate(V1 = gsub("\\r|\\n", "", V1))
请帮忙,先谢谢了
这是一个两步方法,在所需位置添加“_”,然后使用 tidyr 的
separate()
函数将单列分成 4 个。
我在数字后面和字母前面的空格后面添加 _。第二个在字母后面和数字前面的空格后面添加 _。这可以避免与 () 中的数字混淆。
library(tidyr)
score <- "52 (#18) Lincol Lutheran 38 (#22) Gross Alliance"
df <- data.frame(score)
#add a " _" at the desired breaks
score<-gsub( "(\\d )(\\D)", "\\1_\\2", df$score)
score<-gsub( "(\\D )(\\d)", "\\1_\\2", score)
df$score <- score
#Separate the single column into 4
separate(df, score, into=c("Home score", "Home Team", "Visit score", "Visitors"), sep=" _")
# Home score Home Team Visit score Visitors
#1 52 (#18) Lincol Lutheran 38 (#22) Gross Alliance