【问题标题】:Is there any easier way to expand data.frame? [duplicate]有没有更简单的方法来扩展data.frame? [复制]
【发布时间】:2022-01-29 13:16:12
【问题描述】:

我想结合 data1region 。目前,我使用for...,结果为total_df。 有没有更简单的方法?谢谢!

data1 <- data.frame(category=c("a","b","c"),
                    amount=1:3)

region <- data.frame(country=c('US','UK'))


total_df <- data.frame()
for (country in region$country){
  data1$region <- country
  total_df <- rbind(total_df,data1)
}

【问题讨论】:

  • 试试tidyr::crossing(data1, region)

标签: r for-loop


【解决方案1】:

是的!

使用 rep 重构代码,如下所示:

data1 <- data.frame(category=rep(c("a","b","c"),2),
                    amount=rep(1:3,2),
                    country=c(rep("US",3),rep("UK",3)))

> data1
  category amount country
1        a      1      US
2        b      2      US
3        c      3      US
4        a      1      UK
5        b      2      UK
6        c      3      UK

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 2017-05-13
    • 2013-07-07
    • 1970-01-01
    • 2014-04-17
    • 2016-10-05
    相关资源
    最近更新 更多