【问题标题】:R- Convert data into matrix format same as other matrixR-将数据转换为与其他矩阵相同的矩阵格式
【发布时间】:2014-04-22 22:04:19
【问题描述】:

我在 excel 中有如下数据:

     Terms       Category  Weight

      email       TV          1.00

      acccount    Email       12.0

      accept      Phone       3.00

我有其他矩阵,它的格式是:

   Terms   TV    Email  Phone  Contact    Information  Support .....

   achieve  1    0.       0      0         0             0
   acquired 0    10.20    0      0         0             0
   across   0    0        3.00   0          0            0

现在我想把上面的数据转换成上面的格式,比如

   Terms   TV    Email  Phone  Contact    Information  Support .....

    email    1    0.       0      0         0.0          0
    acccount 0    12.0    0      0         0.0          0
    accept   0    0        0      1.23       0          0

我想通过 R 中的程序来执行此操作。任何帮助将不胜感激。提前致谢。

【问题讨论】:

  • 你不能提供一些数据吗?阅读this SO topic 会很有用
  • 是的.. 但是怎么做呢?
  • @Paulo Cardoso 您不能按“条款”合并并获得 OP 想要的结果

标签: r matrix


【解决方案1】:

您需要重塑数据。如果您还没有包“reshape2”,请安装它

这是重塑数据的代码

require(reshape2)
df.reshape <-melt(df, id.var=c("Terms", "Category")) 
#where df is your data.frame to be reshaped
#using both terms and category as ID variables
#now reshape it to wide format by casting
df.wide <-dcast(df.reshape, Terms~Category)

请注意,这将为您的数据中不存在的对提供 NA。 如果你愿意,你可以很容易地用零替换它

这里有一个很好的使用 reshape2 的教程 http://www.seananderson.ca/2013/10/19/reshape.html

【讨论】:

  • 删除dcast中的一个逗号
  • (+1) 很好地使用meltdcast
  • 谢谢你们......得到了我想要的。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
相关资源
最近更新 更多