You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于df1的country列批量为df2添加对应国家列?

为df2添加对应country列的解决方案

方法1:Base R原生实现

  • 提取df1中所有不重复的国家:unique_countries <- unique(df1$country)
  • 确定每个国家需要重复的行数(即df1的总行数):repeat_rows <- nrow(df1)
  • 生成匹配的country向量并添加到df2:df2$country <- rep(unique_countries, each = repeat_rows)

这个逻辑完全匹配你描述的结构:df2按国家分组,每组行数等于df1的总行数,比如前170行对应Denmark、后170行对应France。

方法2:tidyverse/dplyr实现

如果日常使用tidyverse工具链,代码可以更简洁:

library(dplyr)

df2 <- df2 %>%
  mutate(country = rep(unique(df1$country), each = nrow(df1)))

特殊场景适配

如果实际数据中,df2里每个国家的行数和df1中该国家的行数一致(比如df1里Denmark有85行、France有85行,df2对应每组也是85行),可以改用按df1的country列直接重复:

# Base R
df2$country <- rep(df1$country, times = nrow(df2)/nrow(df1))

# dplyr版本
df2 <- df2 %>%
  mutate(country = rep(df1$country, times = nrow(df2)/nrow(df1)))

内容的提问来源于stack exchange,提问作者Rustam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:52:15