我在将XML节点使用R读取到数据框架时遇到了问题。我刚开始阅读XML数据。
这就是我所得到的:
require(dplyr)
require(rvest)
url <- "http://rstudio-pubs-static.s3.amazonaws.com/177866_49f6965521224dd883df5f20f9c32db3.html"
x <- read_html(url) %>%
html_node("code") %>%
html_text()
x1 <- gsub("##", "", x)
df <- read.table(text = x1, fill = TRUE, sep = "\n", header=TRUE, allowEscapes = TRUE)`
但是,read.table()似乎遗漏了一些观察,而没有划分一些行。
我所做的就是将XML文本放到一个简单的数据框架中。HOpefully我可以了解如何更好地处理这些XML内容。
发布于 2016-05-13 11:52:30
我将pre/code
节点拆分成一个向量,然后像注释建议的那样读取表的三个部分
x1 <- strsplit(x, "\n## *")[[1]]
这些是固定宽度的字段,所以对前两个表使用read.fwf
(最后一个表没有任何额外的空格)
length(x1)
[1] 1503
x1[2]
"1 Espresso Leggero 6 2.54 0 1"
zz <- textConnection(x1[2:501])
df1 <- read.fwf(zz, widths=c(3, 18, 10, 12, 12, 13))
close(zz)
names(df1) <- c("Id", strsplit(x1[1], " +")[[1]][-1] )
head(df1)
Id Flavor Intensity WaterVolume CreamVolume SugarPackets
1 1 Espresso Leggero 6 2.54 0 1
2 2 Ristretto 9 0.85 2 0
3 3 Ristretto 9 0.85 1 3
4 4 Lungo Forte 4 1.35 2 0
5 5 Lungo Leggero 2 0.85 1 1
6 6 Lungo Leggero 2 0.85 2 4
zz <- textConnection(x1[503:1002])
df2 <- read.fwf(zz, widths=c(3, 10, 10, 13, 10, 11, 13) )
close(zz)
names(df2) <- c("Id", strsplit(x1[502], " +")[[1]])
df3 <- read.table(text = x1[1004:1503])
names(df3) <- c("Id", strsplit(x1[1003], " +")[[1]])
coffee <- cbind(df1, df2[,-1], df3[,-1])
https://stackoverflow.com/questions/37216279
复制