問題在於如何構建for
循環。不過,首先不要使用它會容易得多,因爲R有很大的支持來遍歷列表,比如lapply
和purrr::map
。你如何組織你的數據的一個版本:
library(tidyverse)
library(rvest)
base_url <- "https://www.whatmobile.com.pk/"
models <- data_frame(model = c("Qmobile_Noir-M6", "Qmobile_Noir-A1", "Qmobile_Noir-E8"),
link = paste0(base_url, model),
page = map(link, read_html))
model_specs <- models %>%
mutate(node = map(page, html_node, '.specs'),
specs = map(node, html_table, header = TRUE, fill = TRUE),
specs = map(specs, set_names, c('var1', 'var2', 'val1', 'val2'))) %>%
select(model, specs) %>%
unnest()
model_specs
#> # A tibble: 119 x 5
#> model var1 var2
#> <chr> <chr> <chr>
#> 1 Qmobile_Noir-M6 Build OS
#> 2 Qmobile_Noir-M6 Build Dimensions
#> 3 Qmobile_Noir-M6 Build Weight
#> 4 Qmobile_Noir-M6 Build SIM
#> 5 Qmobile_Noir-M6 Build Colors
#> 6 Qmobile_Noir-M6 Frequency 2G Band
#> 7 Qmobile_Noir-M6 Frequency 3G Band
#> 8 Qmobile_Noir-M6 Frequency 4G Band
#> 9 Qmobile_Noir-M6 Processor CPU
#> 10 Qmobile_Noir-M6 Processor Chipset
#> # ... with 109 more rows, and 2 more variables: val1 <chr>, val2 <chr>
的數據仍然相當混亂,但至少它都在那裏。
我猜header = FALSE刪除第一行,創建模型向量將變得困難,如果df有更多的記錄 – Janjua
這裏的第一行是一個不是嵌套的描述;如果你想保留它,將'header = FALSE'(儘管它會因爲後面的行結構而重複)。創建模型矢量的正確方法是從菜單中刪除它。 – alistaire
#header = FALSE給出>#A tibble:122 x 5 <感謝您的時間 – Janjua