我有一个来自体育博彩网站的文本文件,想要将这些行转换为数据框。
文本文件如下所示:
18 May 2013 1 X 2 B's
15:30 Augsburg - Greuther 3:1
1.43
4.55
7.27
16
18:30 Dortmund - Hoffenheim 1:2
1.39
5.23
6.79
16
11 May 2013 1 X 2 B's
15:30 Bayer - Hannover 3:1
1.29
5.77
9.46
16
之后数据框应如下所示:
Date Time Team1 Team2 G1 G2 1 0 2
18 May 2013 15:30 Augsburg Greuther 3 1 1.43 4.55 7.27
18 May 2013 18:30 Dortmund Hoffenheim 1 2 1.39 5.23 6.79
11 May 2013 15:30 Bayer Hannover 3 1 1.29 5.77 9.46
我正在考虑一些for循环,我检查我所在的行是否包含日期。我会将变量设置为current_date,如果没有新日期,则不会更新为新日期。 例如,第一个匹配是在同一天,所以日期变量将保持在第二行的May18。
我想生成包含当前日期,时间,队伍1,队伍2,结果(目标1,目标2)的向量,然后是获胜,平局和失败的几率。
然后将它们扯在一起。
我认为我在阅读数据文件的行并检查类型时会遇到的大多数问题。 可以指定在下一个字符是team1之后和“ - ”之后是team2之前和之后“:”是G1和G2并且接下来的三行将被原始包含在该向量中吗?
如果txt文件大约有20,000行,我也不确定for循环是否是最聪明的想法。 也是排除时间之后的第4行。
如果我提出这样的问题,我很抱歉,我知道我可以尝试更长时间的东西并在这里发布我的代码但是我可能最终会得到不充分的半生不熟的代码:/
答案 0 :(得分:1)
这是一次尝试
lines <- readLines("clipboard") # copy the sample text file to clipboard first
lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C")
idx_dates <- strptime(lines, "%d %B %Y")
idx_dates <- which(!is.na(idx_dates))
idx_times <- grep("[0-9]+:[0-9]+", lines)
parse_item <- function(i) {
date <- lines[[max(idx_dates[idx_dates < i])]]
date <- substr(date, 1, nchar(date)-16)
date <- paste(date, substr(lines[[i]], 1, 5))
date <- strptime(date, "%d %B %Y %H:%M")
teamsgoals <- substring(lines[[i]], 9)
teamsgoals <- gsub(" +", " ", teamsgoals)
teamsgoals <- strsplit(teamsgoals, " ")[[1]]
team1 <- teamsgoals[1]
team2 <- teamsgoals[3]
goals <- strsplit(teamsgoals[4], ":")[[1]]
g1 <- as.numeric(goals[1])
g2 <- as.numeric(goals[2])
q1 <- as.numeric(lines[[i+1]])
q0 <- as.numeric(lines[[i+2]])
q2 <- as.numeric(lines[[i+3]])
data.frame(date=date, team1=team1, team2=team2, g1=g1, g2=g2, q1=q1, q0=q0, q2=q2, stringsAsFactors=FALSE)
}
parsed <- lapply(idx_times, FUN=parse_item)
Reduce(rbind, parsed)
Sys.setlocale("LC_TIME", lct)
返回
date team1 team2 g1 g2 q1 q0 q2
1 2013-05-18 15:30:00 Augsburg Greuther 3 1 1.43 4.55 7.27
2 2013-05-18 18:30:00 Dortmund Hoffenheim 1 2 1.39 5.23 6.79
3 2013-05-11 15:30:00 Bayer Hannover 3 1 1.29 5.77 9.46
答案 1 :(得分:0)
此示例提供了有关如何使用Web数据创建数据框的提示。
http://giventhedata.blogspot.com/2012/08/r-and-web-for-beginners-part-iii.html