R是否将数据帧从长格式更改为宽格式?

将下面的数据帧从长格式转换为宽格式的最佳方法是什么?我尝试使用重塑,但未获得理想的结果。


2015    PROD A  test1

2015    PROD A  blue

2015    PROD A  50

2015    PROD A  66

2015    PROD A  66

2018    PROD B  test2

2018    PROD B  yellow

2018    PROD B  70

2018    PROD B  88.8

2018    PROD B  88.8

2018    PROD A  test3

2018    PROD A  red

2018    PROD A  55

2018    PROD A  88

2018    PROD A  90


富国沪深
浏览 637回答 3
3回答

四季花海

为了完整起见,这里是一个使用data.table的便捷rowid()功能的解决方案。问题的关键点是,整形仅仅依赖于行位置的value每一个(内year,product)基团。rowid(year, product)对每个组中的行进行编号。因此,重塑本质上成为一线:library(data.table)dcast(setDT(df1), year + product ~ rowid(year, product, prefix = "col_"))&nbsp; &nbsp;year product col_1&nbsp; col_2 col_3 col_4 col_51: 2015&nbsp; PROD A test1&nbsp; &nbsp;blue&nbsp; &nbsp; 50&nbsp; &nbsp; 66&nbsp; &nbsp; 662: 2018&nbsp; PROD A test3&nbsp; &nbsp; red&nbsp; &nbsp; 55&nbsp; &nbsp; 88&nbsp; &nbsp; 903: 2018&nbsp; PROD B test2 yellow&nbsp; &nbsp; 70&nbsp; 88.8&nbsp; 88.8请注意,使用rowid()一个prefix参数来确保结果列名称在语法上正确。警告:此解决方案假定了这一点,year并为每个组product形成唯一的密钥。数据数据按OP的原样读取,而无需对数据进行任何修改。但是,这需要几行后处理:library(data.table)&nbsp; &nbsp;&nbsp;df1 <- fread("2015&nbsp; &nbsp; PROD A&nbsp; test12015&nbsp; &nbsp; PROD A&nbsp; blue2015&nbsp; &nbsp; PROD A&nbsp; 502015&nbsp; &nbsp; PROD A&nbsp; 662015&nbsp; &nbsp; PROD A&nbsp; 662018&nbsp; &nbsp; PROD B&nbsp; test22018&nbsp; &nbsp; PROD B&nbsp; yellow2018&nbsp; &nbsp; PROD B&nbsp; 702018&nbsp; &nbsp; PROD B&nbsp; 88.82018&nbsp; &nbsp; PROD B&nbsp; 88.82018&nbsp; &nbsp; PROD A&nbsp; test32018&nbsp; &nbsp; PROD A&nbsp; red2018&nbsp; &nbsp; PROD A&nbsp; 552018&nbsp; &nbsp; PROD A&nbsp; 882018&nbsp; &nbsp; PROD A&nbsp; 90",&nbsp;&nbsp; &nbsp; &nbsp; header = FALSE, col.names = c("year", "product", "value"), drop = 2L)[&nbsp; &nbsp; &nbsp; &nbsp; , product := paste("PROD", product)][]

森栏

您正在寻找dcast功能。像这样使用:dcast(data, col1 + col2 ~ col3)这个问题也可能是重复的,因此可以删除。
打开App,查看更多内容
随时随地看视频慕课网APP