3

Possible Duplicate:
Reshape data from long to wide format R

With:

day <- c(1, 1, 2, 2)
prod <- c(1, 2, 1, 2)
cost <- c(20.1, 17.7, 15.2, 23.3)
record <- data.frame(day=day, prod=prod, cost=cost)

record
  day prod cost
1   1    1 20.1
2   1    2 17.7
3   2    1 15.2
4   2    2 23.3

What is a good (quick) way to reshape the data as:

       day_1 day_2
prod_1  20.1  15.2
prod_2  17.7  23.3

Thanks!

4

3 回答 3

6

我们也可以使用xtabs

xtabs(cost ~ prod + day, data = record)

    day
prod    1    2
   1 20.1 15.2
   2 17.7 23.3
于 2012-08-10T19:15:00.927 回答
4

为什么不使用tapply- sum 函数无关紧要,因为您具有唯一值:

> tapply(record$cost,list(record$prod, record$day), FUN=sum)

     1    2
1 20.1 15.2
2 17.7 23.3
于 2012-08-10T19:13:56.100 回答
3

我认为包dcastreshape2有最简单的语法:

library(reshape2)
dcast(prod ~ day, data=record, value.var='cost')

  prod    1    2
1    1 20.1 15.2
2    2 17.7 23.3

然而,这个问题已经被问过很多次了,很可能很快就会结束。

于 2012-08-10T19:12:11.037 回答