首页 > 解决方案 > 如何调整 R 代码以获取 2019 年和 2020 年的数据

问题描述

我有下面的 R 代码,它可以从下表中获取公司 2018 年的财务数据: 桌子

  # Extract all data tables

data1_2 <-webpage2 %>% html_nodes(xpath = '//*[@class="tabElemNoBor overfH fvtDiv"]')

# 从年度损益表中获取数据 error_list_2 <- c() for (j in 1:length(data1_2)){

tryCatch({
  data2_2 <- data1_2[[j]] %>% html_table(fill = TRUE)
  if (grepl("Annual Income Statement", data2_2[1,1])){

    data2_2 <- data2_2[4:nrow(data2_2),]

    units <- data2_2[1,4]
    units <- substr(units, regexpr("Actuals in ", units) + 11, nchar(units))

    year <- data2_2[2,4]
    fiscal <- data2_2[2,1]

    sales_pos <- grep("Sales", data2_2[,1])
    ebitda_pos <- grep("EBITDA", data2_2[,1])
    ebit_pos <- grep("Operating profit", data2_2[,1])
    ebt_pos <- grep("Pre-Tax Profit", data2_2[,1])
    net_income_pos <- grep("Net income", data2_2[,1])
    pe_ratio_pos <- grep("P/E ratio", data2_2[,1])
    eps_pos <- grep("EPS", data2_2[,1])

    sales <- as.numeric(gsub(" ", "", data2_2[sales_pos,4]))
    ebitda <- as.numeric(gsub(" ", "", data2_2[ebitda_pos,4]))
    ebit <- as.numeric(gsub(" ", "", data2_2[ebit_pos,4]))
    ebt <- as.numeric(gsub(" ", "", data2_2[ebt_pos,4]))
    net_income <- as.numeric(gsub(" ", "", data2_2[net_income_pos,4]))
    pe_ratio <- as.numeric(gsub(",", ".", data2_2[pe_ratio_pos,4]))
    eps <- (gsub(",", ".", data2_2[eps_pos,4]))
    eps <- as.numeric(gsub(" ", "", eps))

  }
}, error = function(e) {e; error_list_2 <<- c(error_list_2, j)})

}

您能告诉我如何修改代码以便获取 2019 年和 2020 年的数据吗?

我可以请一个完整的答案,因为我对 R 几乎一无所知,请不要抨击新手 :-)

标签: r

解决方案


推荐阅读