如何在R中正确将长格式数据框转换为宽格式?
将长格式数据框转为宽格式的解决方案
首先构造你提供的原始数据框:
df <- data.frame( Measure = c("Heightpercentile", "Weightpercentile", "Shoesize", "Heightpercentile", "Weightpercentile", "Shoesize", "Heightpercentile", "Weightpercentile", "Shoesize"), Value = c(56,60,10,45,48,7,78,60,9), Person = c("ID4", "ID4", "ID4", "ID6", "ID6", "ID6", "ID7", "ID7", "ID7") )
使用tidyr包的pivot_wider函数可以轻松完成长转宽转换,这是dplyr生态里的标准工具,参数设置正确即可解决问题:
# 首次使用需先安装tidyr包 # install.packages("tidyr") library(tidyr) wide_df <- df %>% pivot_wider( id_cols = Person, # 以Person作为行的唯一标识 names_from = Measure, # 将Measure的取值作为新列名 values_from = Value # 用Value的数值填充对应列 )
运行后得到的结果如下:
> print(wide_df) # A tibble: 3 × 4 Person Heightpercentile Weightpercentile Shoesize <chr> <dbl> <dbl> <dbl> 1 ID4 56 60 10 2 ID6 45 48 7 3 ID7 78 60 9
注:你期望结果中ID6的Weightpercentile是47,但原始数据里对应的Value是48,转换结果会以原始数据为准。
内容的提问来源于stack exchange,提问作者BPott
相关产品推荐
相关产品推荐

