R 使用“创建多个矩阵”;至于;环

R 使用“创建多个矩阵”;至于;环,r,matrix,R,Matrix,我目前在一个统计学班学习多元聚类和分类。在我们的家庭作业中,我们尝试使用10倍交叉验证来测试不同的分类方法在具有三种分类的6变量数据集上的准确度。我希望我能得到一些帮助,创建一个for循环(或者其他我不知道的更好的东西),来创建和运行10个分类和验证,这样我就不必在所有事情上重复自己10次了。。。。这是我的。它将运行,但前两个矩阵仅显示第一个变量。因此,我无法对其他部件进行故障排除 index<-sample(1:10,90,rep=TRUE) table(index) training=

我目前在一个统计学班学习多元聚类和分类。在我们的家庭作业中,我们尝试使用10倍交叉验证来测试不同的分类方法在具有三种分类的6变量数据集上的准确度。我希望我能得到一些帮助,创建一个for循环(或者其他我不知道的更好的东西),来创建和运行10个分类和验证,这样我就不必在所有事情上重复自己10次了。。。。这是我的。它将运行,但前两个矩阵仅显示第一个变量。因此,我无法对其他部件进行故障排除

index<-sample(1:10,90,rep=TRUE)
table(index)
training=NULL
leave=NULL
Trfootball=NULL
football.pred=NULL
for(i in 1:10){
training[i]<-football[index!=i,]
leave[i]<-football[index==i,]
Trfootball[i]<-rpart(V1~., data=training[i], method="class")
football.pred[i]<- predict(Trfootball[i], leave[i], type="class")
table(Actual=leave[i]$"V1", classfied=football.pred[i])}

索引您的问题在于将
数据帧
矩阵
分配给最初设置为
空的向量(
训练
离开
)。一种思考的方式是,你试图把一个完整的矩阵压缩成一个只能接受一个数字的元素。这就是为什么
R
的代码有问题。您需要初始化
training
,并
留给可以处理您的迭代值聚合的对象(@akrun指出的
R
对象
列表

下面的示例应该让您了解正在发生的情况以及可以采取哪些措施来解决问题:

a<-NULL # your set up at the moment
print(a) # NULL as expected
# your football data is either data.frame or matrix
# try assigning those objects to the first element of a:
a[1]<-data.frame(1:10,11:20) # no good
a[1]<-matrix(1:10,nrow=2) # no good either
print(a)

## create "a" upfront, instead of an empty object
# what you need: 
a<-vector(mode="list",length=10)
print(a) # empty list with 10 locations
## to assign and extract elements out of a list, use the "[[" double brackets
a[[1]]<-data.frame(1:10,11:20)
#access data.frame in "a"
a[1] ## no good
a[[1]] ## what you need to extract the first element of the list
## how does it look when you add an extra element?
a[[2]]<-matrix(1:10,nrow=2)
print(a) 

什么是足球?你能展示一下它是什么以及它包含什么吗?我想你可以创建
Trfootball
leave
training
football.pred
等列表,即
Trfootball原始数据football是一个7x90矩阵,第一列中有1-3类,其余的数据由6个观测数据变量填充。下面是一个足球数据的例子。set.seed(90)v1=sample(1:3,90,rep=TRUE)v2=sample(3:46,90,rep=TRUE)v3=sample(7:20,90,rep=TRUE)v4=sample(6:12,90,rep=TRUE)v5=sample(5:15,90,rep=TRUE)v6=sample(11:15,90,rep=TRUE)v7=sample(1:18,90,rep=TRUE)football=cbind(v1,v2,v3,v4,v5,v6,v7)