代码之家  ›  专栏  ›  技术社区  ›  Mark

按列名将表转换为矩阵[重复]

  •  5
  • Mark  · 技术社区  · 16 年前

    我有如下数据框

           models cores     time
    1       4     1 0.000365
    2       4     2 0.000259
    3       4     3 0.000239
    4       4     4 0.000220
    5       8     1 0.000259
    6       8     2 0.000249
    7       8     3 0.000251
    8       8     4 0.000258
    

    ……等

    我想把它转换成一个表格/矩阵,表格/矩阵中有行标签的模型,列标签的核心,以及数据项的时间。

    例如

      1 2 3 4 5 6 7 8    
    1   time data
    4   time data
    

    目前我正在使用for循环将其转换成这个结构,尽管我想知道是否有更好的方法?

    3 回复  |  直到 14 年前
        1
  •  9
  •   Yorgos    16 年前

    检查从整形包强制转换的方法

    # generate test data    
    x <- read.table(textConnection('
    models cores  time
    4 1 0.000365
    4 2 0.000259
    4 3 0.000239
    4 4 0.000220
    8 1 0.000259
    8 2 0.000249
    8 3 0.000251
    8 4 0.000258'
    ), header=TRUE)
    
    
    library(reshape)
    cast(x, models ~ cores)
    

    结果:

      models        1        2        3        4
    1      4 0.000365 0.000259 0.000239 0.000220
    2      8 0.000259 0.000249 0.000251 0.000258
    
        2
  •  5
  •   Aniko    16 年前

    下面是一个使用基函数的版本 reshape :

    y <- reshape(x, direction="wide", v.names="time", timevar="cores", 
                 idvar="models")
    

    随输出

      models   time.1   time.2   time.3   time.4
    1      4 0.000365 0.000259 0.000239 0.000220
    5      8 0.000259 0.000249 0.000251 0.000258
    

    完成整形的艰苦工作后,可以提取所需的零件:

    res <- data.matrix(subset(y, select=-models))
    rownames(res) <- y$models
    colnames(res) <- substr(colnames(res),6,7)
    

    然后你得到矩阵:

             1        2        3        4
    4 0.000365 0.000259 0.000239 0.000220
    8 0.000259 0.000249 0.000251 0.000258
    
        3
  •  4
  •   Alex Brown    16 年前

    你没有 需要 整形包,有一个内置函数 reshape 可以做到的。

    > reshape(x,idvar="models",timevar="cores",direction="wide")
      models   time.1   time.2   time.3   time.4
    1      4 0.000365 0.000259 0.000239 0.000220
    5      8 0.000259 0.000249 0.000251 0.000258