Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将向量元素作为单个参数传递给R中的函数_R - Fatal编程技术网

如何将向量元素作为单个参数传递给R中的函数

如何将向量元素作为单个参数传递给R中的函数,r,R,我正在使用rvest进行一个web抓取项目 html_text(html_nodes(url, CSS)) 从url中提取数据,只要找到匹配的CSS。我的问题是,我正在抓取的网站对每个列出的产品都使用了唯一的CSS ID(例如ListItem\u 001\u Price)。因此,1CSS精确定义了1个商品的价格,因此自动化的网页垃圾处理不起作用 我可以创建一个向量 V <- c("ListItem_001_Price", "ListItem_002_Price", "ListItem_

我正在使用rvest进行一个web抓取项目

html_text(html_nodes(url, CSS)) 
url
中提取数据,只要找到匹配的
CSS
。我的问题是,我正在抓取的网站对每个列出的产品都使用了唯一的
CSS ID
(例如
ListItem\u 001\u Price
)。因此,1
CSS
精确定义了1个商品的价格,因此自动化的网页垃圾处理不起作用

我可以创建一个向量

V <- c("ListItem_001_Price", "ListItem_002_Price", "ListItem_003_Price")

V您可以在此处尝试使用
lappy

V <- c("ListItem_001_Price", "ListItem_002_Price", "ListItem_003_Price")
results <- lapply(V, function(x) html_text(html_nodes(url, x)))
V
html\u nodes()
需要首字母“.”才能按css类查找标记。您可以手动创建


V谢谢蒂姆,它工作得很好!应用程序中的“函数(x)”是我无法理解的——很高兴看到它正常工作。很好的解释,伙计,从你的博文中学到了很多!感谢您在这里分享其他功能。
library(rvest)
# An example piece of html
example_markup <- "<ul>
<li class=\"ListItem_041_Price\">Brush</li>
<li class=\"ListItem_031_Price\">Phone</li>
<li class=\"ListItem_002_Price\">Paper clip</li>
<li class=\"ListItem_012_Price\">Bucket</li>
</ul>"
html <- read_html(example_markup)


# Avoid manual creation of css with regex
regex <- 'ListItem_([0-9]{3})_Price'
# Note that ([0-9]{3}) will match three consecutive numeric characters
price_classes <- regmatches(example_markup, gregexpr(regex, example_markup))[[1]]
# Paste leading "." so that html_nodes() can find the class:
price_classes <- paste(".", price_classes, sep="")

# A singel entry is found like so:
html %>% html_nodes(".ListItem_031_Price") %>% html_text()

# Use sapply to get a named character vector of your products
# Note how ".ListItem_031_Price" from the line above is replaced by x
# which will be each item of price_classes in turn.
products <- sapply(price_classes, function(x) html %>% html_nodes(x) %>% html_text())