如何基于DataFrame现有数据为每个国家新增z-x类型计算行
问题描述
现有如下R数据集:
df <- data.frame(country = c("A", "A", "B", "B", "C", "C"), type = c("x", "z", "x", "z", "x", "z"), value = c(4, 2, 6, 10, 54, 10))
数据预览:
country type value 1 A x 4 2 A z 2 3 B x 6 4 B z 10 5 C x 54 6 C z 10
需要为每个国家(A、B、C)新增一行数据,该行的type为"z-x",value为对应国家z类型与x类型的value差值,最终得到如下结果:
result <- data.frame(country = c("A", "A", "A", "B", "B", "B", "C", "C", "C"), type = c("x", "z", "z-x", "x", "z", "z-x", "x", "z", "z-x"), value = c(4, 2, -2, 6, 10, 4, 54, 10, -44))
结果预览:
country type value 1 A x 4 2 A z 2 3 A z-x -2 4 B x 6 5 B z 10 6 B z-x 4 7 C x 54 8 C z 10 9 C z-x -44
解决方案
方法1:使用dplyr包(tidyverse风格)
先确保安装并加载dplyr包,通过分组计算差值后合并原数据:
library(dplyr) df_result <- df %>% group_by(country) %>% summarise( type = "z-x", value = value[type == "z"] - value[type == "x"], .groups = "drop" ) %>% bind_rows(df) %>% arrange(country, factor(type, levels = c("x", "z", "z-x"))) print(df_result)
方法2:基础R实现
通过循环处理每个国家,计算差值并构建新行后合并:
# 获取所有唯一国家 countries <- unique(df$country) # 初始化存储差值行的列表 diff_rows <- list() for (cntry in countries) { # 筛选当前国家的数据 cntry_data <- df[df$country == cntry, ] # 计算z-x的差值 diff_val <- cntry_data$value[cntry_data$type == "z"] - cntry_data$value[cntry_data$type == "x"] # 构建新行 diff_rows[[cntry]] <- data.frame(country = cntry, type = "z-x", value = diff_val) } # 合并原数据和差值行,再排序 df_result <- rbind(df, do.call(rbind, diff_rows)) df_result <- df_result[order(df_result$country, match(df_result$type, c("x", "z", "z-x"))), ] # 重置行名 row.names(df_result) <- NULL print(df_result)
内容的提问来源于stack exchange,提问作者Pedro Cardoso
相关产品推荐
相关产品推荐

