我对 R 很陌生,正在努力创建一个矩阵。我的教育目标是创建一个方差-协方差矩阵以供进一步分析。我创建了一个自定义函数并获得了所需格式的输出,但它显示 "matrix" "array."
实际上,我只想要 matrix
中的输出。
关于数据: 数据是实际数据的片段。有3个复制(rep)和3个处理(treat),3个字符(dtf、rpp、ppr)。
功能是计算基因型方差-表型矩阵。
data<- structure(list(rep = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L),
treat = c("1", "1", "1", "2", "2", "2", "3", "3", "3"),
dtf = c(51L, 51L, 52L, 52L, 52L, 52L, 52L, 58L, 52L),
rpp = c(4.6667, 6.4, 7.25, 3.5, 6.1, 6.5556, 4.1429, 4, 3.5),
ppr = c(2.6111, 4.8333, 5.463, 3.0167, 5.9, 4.7778, 2.7381, 2.7778, 4.1389)),
row.names = c(NA, 9L),
class = "data.frame")
# Gen Var-Cov
gvcov<- function (data, genotypes, replication) {
convrt<- function(data1) {
data1<- as.data.frame(sapply(data1, as.numeric))
data1<- as.list(data1)
return(data1)
}
datam<- convrt(data)
colnumber<- ncol(data)
headings<- names(data)
analysis<- function(genotypes, replication, trait1, trait2) {
genotypes<- as.factor(genotypes)
replication<- as.factor(replication)
sumch1<- tapply(trait1, genotypes, sum)
sumch2<- tapply(trait2, genotypes, sum)
sumr1<- tapply(trait1, replication, sum)
sumr2<- tapply(trait2, replication, sum)
repli<- nlevels(replication)
genotype<- nlevels(genotypes)
GT1<- sum(trait1)
GT2<- sum(trait2)
CF<- (GT1 * GT2)/(repli * genotype)
TSP<- round(sum(trait1 * trait2) - CF, 4)
GSP<- round((sum(sumch1 * sumch2)/repli) - CF, 4)
RSP<- round((sum(sumr1 * sumr2)/genotype) - CF, 4)
ESP<- TSP - GSP - RSP
DFR<- repli - 1
DFG<- genotype - 1
DFE<- DFR * DFG
RMP<- round(RSP/DFR, 4)
GMP<- round(GSP/DFG, 4)
EMP<- round(ESP/DFE, 4)
ECov<- EMP
GCov<- round((GMP - EMP)/repli, 4)
return(GCov)
}
# matrix
genetic.cov<- c()
index = 0
for (i in 1:(colnumber)) {
for (j in 1:colnumber) {
index = index + 1
genetic.cov[index]<- analysis(genotypes, replication,
datam[[i]], datam[[j]])
}
}
matrix1<- matrix(genetic.cov, nrow = colnumber,
dimnames = list(headings, headings))
return(matrix1)
}
a<- gvcov(d[3:8], d$treat, d$rep)
class(a)