2 回答

TA貢獻1836條經驗 獲得超13個贊
在“ reshape2”中,您可以使用recast(盡管根據我的經驗,這不是眾所周知的功能)。
library(reshape2)
recast(mydf, id ~ variable + type, id.var = c("id", "type"))
# id transactions_expense transactions_income amount_expense amount_income
# 1 20 25 20 95 100
# 2 30 45 50 250 300
您還可以使用基數R reshape:
reshape(mydf, direction = "wide", idvar = "id", timevar = "type")
# id transactions.income amount.income transactions.expense amount.expense
# 1 20 20 100 25 95
# 3 30 50 300 45 250
或者,你可以melt和dcast,像這樣的(這里“data.table”):
library(data.table)
library(reshape2)
dcast.data.table(melt(as.data.table(mydf), id.vars = c("id", "type")),
id ~ variable + type, value.var = "value")
# id transactions_expense transactions_income amount_expense amount_income
# 1: 20 25 20 95 100
# 2: 30 45 50 250 300
在dcast.data.table“ data.table”(1.9.8)的更高版本中,您將可以直接執行此操作。如果我正確理解的話,@ Arun嘗試實現的內容將是在無需首先melt獲取數據的情況下進行重塑,這就是當前發生的情況recast,本質上是melt+ dcast操作序列的包裝。
而且,為徹底起見,這里是tidyr方法:
library(dplyr)
library(tidyr)
mydf %>%
gather(var, val, transactions:amount) %>%
unite(var2, type, var) %>%
spread(var2, val)
# id expense_amount expense_transactions income_amount income_transactions
# 1 20 95 25 100 20
# 2 30 250 45 300 50

TA貢獻1830條經驗 獲得超9個贊
使用data.table v1.9.6 +,我們可以value.var同時轉換多個列(并在中使用多個聚合函數fun.aggregate)。請查看?dcast更多信息以及示例部分。
require(data.table) # v1.9.6+
dcast(dt, id ~ type, value.var=names(dt)[3:4])
# id transactions_expense transactions_income amount_expense amount_income
# 1: 20 25 20 95 100
# 2: 30 45 50 250 300
添加回答
舉報