如何在R中使用for循环组合多个两个数据集

如何在R中使用for循环组合多个两个数据集,r,R,我有两组数据: 日期其中包含2017年的所有日期 国家包含222个国家 我希望country的每个值都包含2017年的所有日期。我创建了一个for循环,但最终输出只是列表中的最后一个国家 for(i in (1:222)){ countries <- rep(country[i,1],365) final <- cbind(countries,dates) } (i in(1:222))的{ 国家/地区您可以使用tidyverse和tibble、列表列和unest 图书馆(

我有两组数据:

  • 日期
    其中包含2017年的所有日期
  • 国家
    包含222个国家
  • 我希望
    country
    的每个值都包含2017年的所有
    日期。我创建了一个for循环,但最终输出只是列表中的最后一个国家

    for(i in (1:222)){
      countries <- rep(country[i,1],365)
      final <- cbind(countries,dates)
    }
    
    (i in(1:222))的
    {
    
    国家/地区您可以使用
    tidyverse
    tibble
    、列表列和
    unest

    图书馆(tidyverse)


    为了回答您的具体问题,我将使用expand.grid():

    这将为您提供
    国家
    日期
    的完整因子组合

    但不能确定这是否是解决问题的最佳方法。我觉得如果必须多次复制数据,则会发生其他情况?

    使用R base,可以使用并生成笛卡尔积(sql中的交叉连接)


    不明白-行是国家,列是日期?国家仅包含1列,这是222个国家的列表,而日期还包含1列,这是2017年的日期。
    tibble(country = country,
           dates = list(dates)) %>%
    unnest()
    
    dates = seq(as.Date('2017-01-01'), as.Date('2017-01-04'), by = 'days')
    country = c('usa', 'brazil', 'austalia', 'sweden')
    
    dates_country = setNames(expand.grid(dates, country), c('dates', 'country'))
    
    # create list of dataframes by country for further manipulation
    split(dates_country, dates_country$country)
    
    merge(country, dates, all=TRUE)