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)][]
- 3 回答
- 0 關注
- 667 瀏覽
添加回答
舉報