将表转换为矩阵

时间:2015-05-11 17:17:33

标签: r

在这张图片中,我想将我的桌子(在左侧)安排到一个包含3行的桌子(右侧)。

https://drive.google.com/file/d/0B4GgTf6nYI4YMHltWjRkeDhob3M/view?usp=sharing

也就是说,我有一张这样的表

     0      3       6       9       13      16      31     64
N    100,0  98,7    96,7    97,5    91,2    15,7    0,4   0,6
N1   100,0  102,0   97,8    98,6    89,8    11,0    0,3   0,2

并希望像这样安排:

Alkanes Time    Degradation
N   0   100,0
N   3   98,7
N   6   96,7
N   9   97,5
N   13  91,2
N   16  15,7
N   31  0,4
N   64  0,6
N1  0   100,0
N1  3   102,0
N1  6   97,8
N1  9   98,6
N1  13  89,8
N1  16  11,0
N1  31  0,3
N1  64  0,2

示例数据:

x <- structure(list(X = structure(1:3, .Label = c("N", "N1", "N2"), class = "factor"), X0 = c(100, 100, 100), X3 = c(98.7, 102, 95.1), X6 = c(96.7, 97.8, 94.5), X9 = c(97.5, 98.6, 101), X13 = c(91.2, 89.8, 89.4), X16 = c(15.7, 11, 22.5), X31 = c(0.4, 0.3, 0), X64 = c(0.6, 0.2, 0)), .Names = c("X", "X0", "X3", "X6", "X9", "X13", "X16", "X31", "X64"), class = "data.frame", row.names = c(NA, -3L))

期望的输出:

y <- structure(list(Alkanes = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("N", "N1", "N2"), class = "factor"), Time = c(0L, 3L, 6L, 9L, 13L, 16L, 31L, 64L, 0L, 3L, 6L, 9L, 13L, 16L, 31L, 64L, 0L, 3L, 6L, 9L, 13L, 16L, 31L, 64L), Degradation = c(100, 98.7, 96.7, 97.5, 91.2, 15.7, 0.4, 0.6, 100, 102, 97.8, 98.6, 89.8, 11, 0.3, 0.2, 100, 95.1, 94.5, 101, 89.4, 22.5, 0, 0)), .Names = c("Alkanes", "Time", "Degradation"), class = "data.frame", row.names = c(NA, -24L))

2 个答案:

答案 0 :(得分:0)

你可以尝试

library(reshape2)
names(my_data) <- sub('[^0-9]+', '', names(my_data))

m1 <- as.matrix(my_data[-1])
row.names(m1) <- my_data[,1]
d1 <- melt(m1)
d2 <- setNames(d1[order(d1$Var1),], c('Alkanes', 'Time', 'Degradation'))

或者

my_data1 <- my_data[-1]
dN <- data.frame(Alkanes= my_data[1][row(my_data1)],
   Time= names(my_data1)[col(my_data1)], Degradation=unlist(my_data1))
dN1 <- dN[order(dN[,1]),]
row.names(dN1) <- NULL

答案 1 :(得分:0)

将“x”表示为:

x
#    X  X0    X3   X6    X9  X13  X16 X31 X64
# 1  N 100  98.7 96.7  97.5 91.2 15.7 0.4 0.6
# 2 N1 100 102.0 97.8  98.6 89.8 11.0 0.3 0.2
# 3 N2 100  95.1 94.5 101.0 89.4 22.5 0.0 0.0

您可以尝试以下内容:

as.data.frame(
  as.table(
    `dimnames<-`(as.matrix(x[-1]), list(x[[1]], gsub("X", "", names(x)[-1])))))
#    Var1 Var2  Freq
# 1     N    0 100.0
# 2    N1    0 100.0
# 3    N2    0 100.0
# 4     N    3  98.7
# 5    N1    3 102.0
# 6    N2    3  95.1
# 7     N    6  96.7
# 8    N1    6  97.8
# 9    N2    6  94.5
# 10    N    9  97.5
# 11   N1    9  98.6
# 12   N2    9 101.0
# 13    N   13  91.2
# 14   N1   13  89.8
# 15   N2   13  89.4
# 16    N   16  15.7
# 17   N1   16  11.0
# 18   N2   16  22.5
# 19    N   31   0.4
# 20   N1   31   0.3
# 21   N2   31   0.0
# 22    N   64   0.6
# 23   N1   64   0.2
# 24   N2   64   0.0

从那里开始,它只是对列进行排序和重命名,这是相当标准的操作。