亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 667 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號