【问题标题】:Create new dataframes based on a list in R基于 R 中的列表创建新的数据框
【发布时间】:2020-08-27 16:23:00
【问题描述】:

我想创建大约 20 个新数据框,并且我希望这些数据框的名称为“matches_[country]”,其中 [country] 是 countries_list 中的国家/地区名称。我认为 for 循环会是解决方案,但我无法让它工作。

这是我尝试过的(结果是df):

countries_list = list('Netherlands', 'England', 'Brazil', 'Argentina', 'Germany', 'France', 'Spain', 'Italy', 'Portugal', 'Croatia', 'Uruguay', 'Mexico')

for (i in countries_list) {
  matches_i = filter(results, home_team == 'i' | away_team == 'i')
}

有了这个,我想我会得到列表中每个国家/地区的数据框,每个数据框中包含该国家/地区进行的所有比赛,无论是主队还是客队。但是,它会创建没有任何数据的 matches_i。

编辑:结果是一个包含国际足球比赛的表格,每场比赛是一行,列是日期、主队、客队、主队得分、客队得分、锦标赛等。

我该如何解决这个问题?

【问题讨论】:

标签: r list loops indexing


【解决方案1】:

你有一些好主意。 但是在对象名上添加 i 不会匹配“matches_[country]”。你最终会得到一个名为matches_i的对象。并且 home_team == 'i' 将寻找一个名为 i 的国家而不是实际的国家名称(这就是您的数据框为空的原因。没有名为 i 的国家)。 home_team == i(不带引号)可以解决问题。

所以我组成了一个较小的results 数据集和一个较短的countries 列表作为示例。

results <- data.frame(home_team = c('Netherlands', 'England', 'Brazil'),
                      away_team = c("Spain", "Italy", "England"))

countries <- list('Netherlands', 'England', "Brazil", "Spain", "Italy") 

这是为列表中的每个国家/地区生成数据集的循环。

                       
for (i in countries) {
  matches <- filter(results, home_team == i | away_team == i)
  assign(paste("matches_", i, sep = ""), matches)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2015-04-21
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    相关资源
    最近更新 更多