R:如何在列表中存储列表?

瑞安·考德威尔(Ryan Caldwell)

我正在尝试从balloon-reference.com的表中解析数据。我想在多个团队和多个年份这样做。下面的代码用于捕获每个团队赛季链接。

library(XML)

#Will use for loop to fill in the rest of the link
link_base <- "http://www.baseball-reference.com/teams/"
#List of teams
teams <- c("CHC", "STL")
#Year
season <- 2000:2002
#End of link
end_link <- "-schedule-scores.shtml"

links <- list()
for(i in 1:length(teams)){
  links[[i]] <- NaN*seq(length(teams))
  for(j in 1:length(season)){
    links[[i]][j] <- paste0(link_base, teams[i], "/", season[j], end_link)
  }
}

结果是:

> links
[[1]]
[1] "http://www.baseball-reference.com/teams/CHC/2000-schedule-scores.shtml"
[2] "http://www.baseball-reference.com/teams/CHC/2001-schedule-scores.shtml"
[3] "http://www.baseball-reference.com/teams/CHC/2002-schedule-scores.shtml"

[[2]]
[1] "http://www.baseball-reference.com/teams/STL/2000-schedule-scores.shtml"
[2] "http://www.baseball-reference.com/teams/STL/2001-schedule-scores.shtml"
[3] "http://www.baseball-reference.com/teams/STL/2002-schedule-scores.shtml"

现在,对于列表中的每个元素,我想使用readHTMLTable函数,以便我可以解析信息。我尝试这样做:

a <- list()
for(i in 1:length(teams)){
  a[[i]] <- NaN*seq(length(teams))
  for(j in 1:length(season)){
    a[[i]][j] <- readHTMLTable(links[[i]][j])
  }
}

readHTMLTable返回长度为6的列表:

x <- readHTMLTable(links[[1]][1])
> length(x)
[1] 6

我希望列表的第一个元素存储到“ CHC”链接的readHTMLTable函数的输出中。我希望列表的第二个元素存储来自readHTMLTable函数的“ STL”链接的输出。因此,列表a将包含2个元素。这两个元素都将包含3个列表,其中包含6个元素。

罗夏

我认为这有效

lst <- lapply(links, function(l) lapply(l, function(x) readHTMLTable(x)))

length(lst)
# [1] 2
lengths(lst)
# [1] 3 3

第一个子列表应具有CHC,第二个子列表应具有STL。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章