为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

富国沪深 2019-12-06 14:52:20
将下面的数据帧从长格式转换为宽格式的最佳方法是什么?我尝试使用重塑,但未获得理想的结果。2015    PROD A  test12015    PROD A  blue2015    PROD A  502015    PROD A  662015    PROD A  662018    PROD B  test22018    PROD B  yellow2018    PROD B  702018    PROD B  88.82018    PROD B  88.82018    PROD A  test32018    PROD A  red2018    PROD A  552018    PROD A  882018    PROD A  90
查看完整描述

3 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

为了完整起见,这里是一个使用data.table的便捷rowid()功能的解决方案。


问题的关键点是,整形仅仅依赖于行位置的value每一个(内year,product)基团。rowid(year, product)对每个组中的行进行编号。因此,重塑本质上成为一线:


library(data.table)

dcast(setDT(df1), year + product ~ rowid(year, product, prefix = "col_"))

   year product col_1  col_2 col_3 col_4 col_5

1: 2015  PROD A test1   blue    50    66    66

2: 2018  PROD A test3    red    55    88    90

3: 2018  PROD B test2 yellow    70  88.8  88.8

请注意,使用rowid()一个prefix参数来确保结果列名称在语法上正确。


警告:此解决方案假定了这一点,year并为每个组product形成唯一的密钥。


数据

数据按OP的原样读取,而无需对数据进行任何修改。但是,这需要几行后处理:


library(data.table)    

df1 <- fread("

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", 

      header = FALSE, col.names = c("year", "product", "value"), drop = 2L)[

        , product := paste("PROD", product)][]


查看完整回答
反对 回复 2019-12-06
?
森栏

TA贡献1810条经验 获得超5个赞

您正在寻找dcast功能。像这样使用:


dcast(data, col1 + col2 ~ col3)


这个问题也可能是重复的,因此可以删除。


查看完整回答
反对 回复 2019-12-06
  • 3 回答
  • 0 关注
  • 580 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信