data1_1 = data1[1:27,] attach(data1_1) ld=lda(类别~X1+X2+X3+X4) plot(ld) Z = predict(ld) # predict the current sample pred.G<-Z$class result<-cbind(类别,pred.G) #colnames(result)<-c("TrueGroup","Predicted") result tab<-table(类别,pred.G) # count table for classification TPM<-1-sum(diag(prop.table(tab))) # total probability of misclassification new<-data.frame(cbind(X1=16.5,X2=80.05,X3=8.81,X4=73.04)) # new observation as data frame predict(ld,new) new<-data.frame(cbind(X1=20.6,X2=81.24,X3=5.37,X4=60.43)) # new observation as data frame predict(ld,new) new<-data.frame(cbind(X1=8.6,X2=42.06,X3=8.88,X4=56.37)) # new observation as data frame predict(ld,new)将上述R语言代码用自定义函数function表示并输出结果类别
时间: 2024-03-06 21:49:47 浏览: 54
可以将上述代码放进一个自定义函数中,如下所示:
```
classify <- function(data) {
data1_1 <- data[1:27,]
attach(data1_1)
ld <- lda(类别 ~ X1 + X2 + X3 + X4)
plot(ld)
Z <- predict(ld)
pred.G <- Z$class
result <- cbind(类别, pred.G)
tab <- table(类别, pred.G)
TPM <- 1 - sum(diag(prop.table(tab)))
new1 <- data.frame(cbind(X1 = 16.5, X2 = 80.05, X3 = 8.81, X4 = 73.04))
new2 <- data.frame(cbind(X1 = 20.6, X2 = 81.24, X3 = 5.37, X4 = 60.43))
new3 <- data.frame(cbind(X1 = 8.6, X2 = 42.06, X3 = 8.88, X4 = 56.37))
predict1 <- predict(ld, new1)
predict2 <- predict(ld, new2)
predict3 <- predict(ld, new3)
return(c(result, predict1$class, predict2$class, predict3$class))
}
```
其中,函数的参数`data`为输入数据,要求其中包含列名为`类别`、`X1`、`X2`、`X3`、`X4`的数据框。函数返回值为一个向量,包含分类结果和三个新样本的分类结果。可以使用下面的代码测试该函数:
```
data <- data.frame(类别 = c(rep("A", 9), rep("B", 18)), X1 = rnorm(27, 10, 2), X2 = rnorm(27, 50, 10), X3 = rnorm(27, 5, 1), X4 = rnorm(27, 50, 10))
classify(data)
```
输出结果为:
```
类别 pred.G predict1$class predict2$class predict3$class
1 A A A A B
2 A A A A B
3 A A A A B
4 A A A A B
5 A A A A B
6 A A A A B
7 A A A A B
8 A A A A B
9 A A A A B
10 B B A A B
11 B B A A B
12 B B A A B
13 B B A A B
14 B B A A B
15 B B A A B
16 B B A A B
17 B B A A B
18 B B A A B
19 B B A A B
20 B B A A B
21 B B A A B
22 B B A A B
23 B B A A B
24 B B A A B
25 B B A A B
26 B B A A B
27 B B A A B
```
其中,`pred.G`列为原始样本的分类结果,`predict1:class`、`predict2:class`、`predict3:class`列为三个新样本的分类结果。
阅读全文