作为R的新手,我有一个关于写入和读取矢量数据的问题。
我的例子1
n = 100 g = 6 set.seed(g) d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))), y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2)))) plot(d) require(vegan) fit <- cascadeKM(scale(d, center = TRUE, scale = TRUE), 1, 10, iter = 1000) plot(fit, sortg = TRUE, grpmts.plot = TRUE) calinski.best <- as.numeric(which.max(fit$results[2,])) cat("Calinski criterion optimal number of clusters:", calinski.best, "\n")
(来源),它按预期打印Calinski准则最优簇数:5。
示例2:(先写入数据帧d,然后读取)
n = 100 g = 6 set.seed(g) d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))), y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2)))) write.table(d, "d.txt", sep='\t', quote=FALSE) #write data frame d = read.table("d.txt", header=TRUE, sep = '\t') #read later plot(d) require(vegan) fit <- cascadeKM(scale(d, center = TRUE, scale = TRUE), 1, 10, iter = 1000) plot(fit, sortg = TRUE, grpmts.plot = TRUE) calinski.best <- as.numeric(which.max(fit$results[2,])) cat("Calinski criterion optimal number of clusters:", calinski.best, "\n")
然而,示例2打印"Calinski准则最优簇数:1"。
我认为在R中的文件IO后,格式(或其他内容)发生了更改。但我不知道R如何读取和写入数字。谁能给我一些线索,谢谢。
如果文件写入时没有列名称和行名称,则编辑,问题已解决。
write.table(d, "d.txt", sep='\t', quote=FALSE, row.name=FALSE, col.names=FALSE)
读取时,R还读取行和列名称,。另一个方法是在阅读时避开这些名字。
无法为一个组计算卡林斯基索引,但它会变成Inf或-Inf。在第一个示例中,它恰好是-Inf,在第二个示例中,它恰好是Inf,当您查找哪个组时。max
,Inf就是你得到的。我不知道我们为什么要费心计算一个类案例的索引,但是如果你搜索最佳结果,你应该忽略第一个案例。我们在plot
命令中这样做,在这两种情况下,给出五个集群作为最佳结果。以下对代码的修改将在两种情况下给出相同的答案:
calinski.best <- as.numeric(which.max(fit$results[2,-1])) + 1
cat("Calinski criterion optimal number of clusters:", calinski.best, "\n")
我们必须有1
,因为我们省略了一列。
Inf/-Inf不确定性的小细节。正如您在中看到的那样?卡林斯基准则定义为(SSB/(K-1))/(SSW/(n-K)),对于一组K=1,SSB/0=Inf。对于一组,SSB=0,但计算为零,在数字计算机中很少精确,在我的计算机中,零是-2.8e-14和-2.8e-14/0=-Inf。在第二个示例中,SSB=2.8e-14和2.8e-14/0=Inf。在寻找最佳值时,忽略第一列。有时SSB可以精确为零,然后0/0=NaN(不是数字)。