R 按列名将表转换为矩阵
我的数据框如下所示R 按列名将表转换为矩阵,r,statistics,R,Statistics,我的数据框如下所示 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 。。。等 我想将其转
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
。。。等
我想将其转换为一个表/矩阵,其中#models表示行标签,core表示列标签,time表示数据条目
e、 g
目前我正在使用for循环将其转换为这种结构,不过我想知道是否有更好的方法?检查从重塑包转换的方法
# 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)
下面是一个使用基本函数重塑的版本:
y <- reshape(x, direction="wide", v.names="time", timevar="cores",
idvar="models")
通过艰苦的整形工作,您可以提取所需的零件:
res <- data.matrix(subset(y, select=-models))
rownames(res) <- y$models
colnames(res) <- substr(colnames(res),6,7)
你不需要重塑软件包,有一个内置的函数revorme
可以做到这一点
> 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
看起来我没有对包进行重塑,但我发现这也可以:tapply(f[,3],f[,1:2],c)有一个实现这一点的各种方法的列表。
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
> 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