使用 Reshape Cast

Using Reshape Cast

我正在尝试通过以下方式重塑示例数据框。

df<-data.frame(market = c("a","b","c","a","b","c"),companyName =  c("foo","foo","foo", "bar","bar","bar"), val = seq(1,6))
require(reshape)
dfNew <- cast(df,market ~ companyName+companyName)

生成:

      market        company 1   company 2    
1      a                1           4
2      b                2           5
3      c                3           6

但是我得到这个错误:

Using val as value column.  Use the value argument to cast to override this choice
Error in `[.data.frame`(data, , variables, drop = FALSE) : 
  undefined columns selected

reshapereshape2 此时都是已弃用的包。如果您使用 Hadley 的最新版本,tidyr:

spread(df, key = companyName, value = val)

  market bar foo
1      a   4   1
2      b   5   2
3      c   6   3