第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

R是否將數(shù)據(jù)幀從長格式更改為寬格式?

R是否將數(shù)據(jù)幀從長格式更改為寬格式?

富國滬深 2019-12-06 14:52:20
將下面的數(shù)據(jù)幀從長格式轉(zhuǎn)換為寬格式的最佳方法是什么?我嘗試使用重塑,但未獲得理想的結(jié)果。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貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個贊

為了完整起見,這里是一個使用data.table的便捷rowid()功能的解決方案。


問題的關(guān)鍵點(diǎn)是,整形僅僅依賴于行位置的value每一個(內(nèi)year,product)基團(tuán)。rowid(year, product)對每個組中的行進(jìn)行編號。因此,重塑本質(zhì)上成為一線:


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參數(shù)來確保結(jié)果列名稱在語法上正確。


警告:此解決方案假定了這一點(diǎn),year并為每個組product形成唯一的密鑰。


數(shù)據(jù)

數(shù)據(jù)按OP的原樣讀取,而無需對數(shù)據(jù)進(jìn)行任何修改。但是,這需要幾行后處理:


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)][]


查看完整回答
反對 回復(fù) 2019-12-06
?
森欄

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個贊

您正在尋找dcast功能。像這樣使用:


dcast(data, col1 + col2 ~ col3)


這個問題也可能是重復(fù)的,因此可以刪除。


查看完整回答
反對 回復(fù) 2019-12-06
  • 3 回答
  • 0 關(guān)注
  • 665 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號