在网页抓取的空白值中插入 NA [英] Inserting NA in blank values from web scraping

查看:56
本文介绍了在网页抓取的空白值中插入 NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些数据抓取到一个数据框中,并且得到了一些空字段,而我更喜欢在其中使用 NA.我试过 na.strings,但要么是把它放在错误的地方,要么就是不工作,我试图 gsub 任何从行首到行尾的空白,但这没有用.

I am working on scraping some data into a data frame, and am getting some empty fields, where I would instead prefer to have NA. I have tried na.strings, but am either placing it in the wrong place or it just isn't working, and I tried to gsub anything that was whitespace from beginning of line to end, but that didn't work.

htmlpage <- read_html("http://www.gourmetsleuth.com/features/wine-cheese-pairing-guide")
sugPairings <- html_nodes(htmlpage, ".meta-wrapper")
suggestions <- html_text(sugPairings)
suggestions <- gsub("\\r\\n", '', suggestions)

如何将空白字段与 NA 分出,无论是在将其添加到数据框中后,还是在添加之前.

How can I sub out the blank fields with NA, either once it is added to the data frame, or before adding it.

推荐答案

rvest::html_text 有一个内置的修剪选项设置 trim=TRUE.完成此操作后,您可以使用例如ifelse 测试空字符串 (=="") 或使用 nzchar.

rvest::html_text has an build in trimming option setting trim=TRUE. After you have done this you can use e.g. ifelse to test for an empty string (=="") or use nzchar.

我完全可以这样做:

html_nodes(htmlpage, ".meta-wrapper") %>% html_text(trim=TRUE) %>% ifelse(. == "", NA, .)

或者这个:

res <- html_nodes(htmlpage, ".meta-wrapper") %>% html_text(trim=TRUE)
res[!nzchar(res)] <- NA_character_

@Richard Scriven 改进:

@Richard Scriven improvement:

html_nodes(htmlpage, ".meta-wrapper") %>% html_text(trim=TRUE) %>% replace(!nzchar(.), NA)

这篇关于在网页抓取的空白值中插入 NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆