如何在R语言中将data.frame的Variables列转为独立列实现数据重塑?
数据重塑:长表转宽表解决方案
要将你的长格式数据转换为指定的宽格式,以下是两种常用的R语言实现方法:
方法一:使用tidyverse的tidyr包(推荐)
tidyverse是当前R数据处理的主流工具集,pivot_wider函数专门用于长表转宽表:
首先加载tidyverse包(如果未安装先执行install.packages("tidyverse")):
library(tidyverse) # 生成原始数据 df1 <- data.frame(Names= c(c(rep("Lincon",12), rep("Joe",12),rep("Megi",12))), Year= c(rep(c(rep(2002,4), rep(2003,4), rep(2004,4)),3)), Values= c(c(c(600, 400,210, 41),c(450, 349, 250, 42), c(200, 300,150, 43), c(500, 436, 200, 52), c(820,480,400, 53), c(500, 210, 279,54), c(701, 340, 112,45), c(195, 480, 120,46),c(550, 452, 111,47))), Variables= rep(c("savings","food", "transport","age"),9)) # 转换为宽表 wide_df <- df1 %>% pivot_wider( id_cols = c(Names, Year), # 作为分组依据的列 names_from = Variables, # 要转换为列名的字段 values_from = Values # 对应填充的值字段 ) # 查看结果 print(wide_df)
执行后会得到你需要的格式:
# A tibble: 9 × 6 Names Year savings food transport age <chr> <dbl> <dbl> <dbl> <dbl> <dbl> 1 Lincon 2002 600 400 210 41 2 Lincon 2003 450 349 250 42 3 Lincon 2004 200 300 150 43 4 Joe 2002 500 436 200 52 5 Joe 2003 820 480 400 53 6 Joe 2004 500 210 279 54 7 Megi 2002 701 340 112 45 8 Megi 2003 195 480 120 46 9 Megi 2004 550 452 111 47
方法二:使用reshape2包的dcast函数
如果你习惯使用reshape2包,也可以用dcast函数实现:
先安装并加载reshape2包(未安装则执行install.packages("reshape2")):
library(reshape2) # 转换为宽表 wide_df2 <- dcast(df1, Names + Year ~ Variables, value.var = "Values") # 查看结果 print(wide_df2)
得到的结果和方法一完全一致。
内容的提问来源于stack exchange,提问作者Emmanuel
相关产品推荐
相关产品推荐

