首先欢迎大家交流!所以我在你的代码中改变了一些东西,比如你只需要 6 个宽度,你有一个额外的列,所以我把它去掉了。当我从网上提取数据时,我注意到第一行很奇怪,所以我只是把它们放在一起,然后再手动添加。
data <- read.fwf('http://masseyratings.com/scores.php?s=285971&sub=14342&all=1&mode=3&sch=on&format=0',widths=c(10,26,3,26,3,4), sep = "\t", header = FALSE, skip = 8)
# This line subsets the data so you don't have that "junk" at the bottom and deletes the row
# with the html tagging.
data <- data[2:2424,]
data <- data.frame(data)
# Create a vector that has the column headers
names <- c("date", "Team1","Runs", "Team 2","Runs","Something")
colnames(data) <- names
# Create the first row of data that we previously deleted.
firstrow = data.frame("2016-04-03", "@Pirates", 4, "Cardinals",1,"")
colnames(firstrow) <- names
finaldata <- rbind.data.frame(firstrow,data)
如果您可以发布您认为垃圾内容的屏幕截图,以供将来参考,这将对试图帮助您解决问题的人有所帮助。
更新
data <- read.fwf('http://masseyratings.com/scores.php?s=285971&sub=14342&all=1&mode=3&sch=on&format=0',
widths=c(10,26,3,26,3,4), sep = "\t", header = FALSE, skip = 9)
data <- data.frame(data)
# This line subsets the data so you don't have that "junk" at the bottom and deletes the row
# with the html tagging.
firstrow <- read.fwf('http://masseyratings.com/scores.php?s=285971&sub=14342&all=1&mode=3&sch=on&format=0',
widths=c(-8,-1,-1,9,26,3,26,3,4), sep = "\t", header = FALSE, n = 1, skip = 8)
firstrow <- data.frame(firstrow,stringsAsFactors=FALSE)
firstrow[,1] <- paste("2",firstrow[1,1],sep = "")
# Create a vector that has the column headers
names <- c("date", "Team1","Runs", "Team 2","Runs","Something")
colnames(data) <- names
colnames(firstrow) <- names
finaldata <- rbind.data.frame(firstrow,data)
移动数据的列的负值,我只是玩弄它直到它解决了,所以第一行中缺少的所有东西都是“2”。然后我粘贴“2”并使用 rbind 函数创建完整的数据框。我希望这可以帮助你。
我也在这个页面上测试过:http://masseyratings.com/scores.php?s=285971&sub=14342&all=1&mode=2&sch=on&format=0
它按预期工作。