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

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個贊
您正在尋找dcast功能。像這樣使用:
dcast(data, col1 + col2 ~ col3)
這個問題也可能是重復(fù)的,因此可以刪除。
- 3 回答
- 0 關(guān)注
- 665 瀏覽
添加回答
舉報