2

我有一个看起来像这样的数据框:

> 塔
   排名 omp ALLA1
1 512 4 772.9
2 1024 2 769.9
3 2048 1 914.2
4 256 8 932.3
5 128 16 1352.0
6 256 16 948.4
7 512 8 761.5
8 1024 4 667.9
9 2048 2 744.9
10 4096 1 956.7

我想最终得到某种矩阵,如下所示:

    256 512 1024 2048 4096
 1 914.2 956.7
 2 769.9 744.9
 4 772.9 667.9
 8 932.3 761.5
16

我不太在意丢失的条目中出现的内容。

4

4 回答 4

3

尝试这个:

> xtabs(ALLA1 ~ omp + ranks, ta)
    ranks
omp     128    256    512   1024   2048   4096
  1     0.0    0.0    0.0    0.0  914.2  956.7
  2     0.0    0.0    0.0  769.9  744.9    0.0
  4     0.0    0.0  772.9  667.9    0.0    0.0
  8     0.0  932.3  761.5    0.0    0.0    0.0
  16 1352.0  948.4    0.0    0.0    0.0    0.0
于 2011-03-30T11:55:14.270 回答
1

运行这个:

with(ta, reshape(ta[order(omp, ranks),], v.names="ALLA1", idvar="omp",
  timevar="ranks", direction="wide"))

你会得到非常相似的东西:

  omp ALLA1.2048 ALLA1.4096 ALLA1.1024 ALLA1.512 ALLA1.256 ALLA1.128
3   1      914.2      956.7         NA        NA        NA        NA
2   2      744.9         NA      769.9        NA        NA        NA
1   4         NA         NA      667.9     772.9        NA        NA
4   8         NA         NA         NA     761.5     932.3        NA
5  16         NA         NA         NA        NA     948.4      1352
于 2011-03-30T11:06:06.473 回答
0

写一个重建ta数据框的答案可能很有用:

lines = "   ranks omp  ALLA1
1    512   4  772.9
2   1024   2  769.9
3   2048   1  914.2
4    256   8  932.3
5    128  16 1352.0
6    256  16  948.4
7    512   8  761.5
8   1024   4  667.9
9   2048   2  744.9
10  4096   1  956.7"
cn = as.character(read.fwf(textConnection(lines), width=c(3, 5, 4, 7),
  stringsAsFactors=FALSE, strip.white=TRUE)[1,])
ta = read.fwf(textConnection(lines), width=c(3, 5, 4, 7), skip=1,
  col.names=cn)[,-1]
于 2011-03-30T10:40:10.637 回答
0

好吧,有人应该展示如何使用行/列索引来做到这一点......

ta <- structure(list(ranks = c(512L, 1024L, 2048L, 256L, 128L, 256L, 
512L, 1024L, 2048L, 4096L), omp = c(4L, 2L, 1L, 8L, 16L, 16L, 
8L, 4L, 2L, 1L), ALLA1 = c(772.9, 769.9, 914.2, 932.3, 1352, 
948.4, 761.5, 667.9, 744.9, 956.7)), .Names = c("ranks", "omp", 
"ALLA1"), class = "data.frame", row.names = c(NA, -10L))

out <- with(ta, {
  ranks <- factor(ranks)
  omp <- factor(omp)
  out <- matrix(nrow=nlevels(omp), ncol=nlevels(ranks), 
                dimnames=list(levels(omp), levels(ranks)))
  out[cbind(omp, ranks)] <- ALLA1
  out
})

结果是

> print(out, na="")
    128   256   512  1024  2048  4096
1                         914.2 956.7
2                   769.9 744.9      
4             772.9 667.9            
8       932.3 761.5                  
16 1352 948.4  
于 2011-04-28T07:26:44.283 回答