我有一个数据,其元素中包含一些NA值。 我想要做的是执行群集而不删除行 NA存在的地方。
我理解gower
中的daisy
距离度量允许这种情况。
但为什么我的代码不起作用?
我欢迎除“雏菊”之外的其他选择。
# plot heat map with dendogram together.
library("gplots")
library("cluster")
# Arbitrarily assigning NA to some elements
mtcars[2,2] <- "NA"
mtcars[6,7] <- "NA"
mydata <- mtcars
hclustfunc <- function(x) hclust(x, method="complete")
# Initially I wanted to use this but it didn't take NA
#distfunc <- function(x) dist(x,method="euclidean")
# Try using daisy GOWER function
# which suppose to work with NA value
distfunc <- function(x) daisy(x,metric="gower")
d <- distfunc(mydata)
fit <- hclustfunc(d)
# Perform clustering heatmap
heatmap.2(as.matrix(mydata),dendrogram="row",trace="none", margin=c(8,9), hclust=hclustfunc,distfun=distfunc);
我收到的错误信息是:
Error in which(is.na) : argument to 'which' is not logical
Calls: distfunc.g -> daisy
In addition: Warning messages:
1: In data.matrix(x) : NAs introduced by coercion
2: In data.matrix(x) : NAs introduced by coercion
3: In daisy(x, metric = "gower") :
binary variable(s) 8, 9 treated as interval scaled
Execution halted
在一天结束时,我想使用NA允许的数据执行层次聚类。
更新
使用上面的示例转换as.numeric
。
但是,当从文本文件中读取时,为什么此代码失败?
library("gplots")
library("cluster")
# This time read from file
mtcars <- read.table("http://dpaste.com/1496666/plain/",na.strings="NA",sep="\t")
# Following suggestion convert to numeric
mydata <- apply( mtcars, 2, as.numeric )
hclustfunc <- function(x) hclust(x, method="complete")
#distfunc <- function(x) dist(x,method="euclidean")
# Try using daisy GOWER function
distfunc <- function(x) daisy(x,metric="gower")
d <- distfunc(mydata)
fit <- hclustfunc(d)
heatmap.2(as.matrix(mydata),dendrogram="row",trace="none", margin=c(8,9), hclust=hclustfunc,distfun=distfunc);
我得到的错误是:
Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
3: In min(x) : no non-missing arguments to min; returning Inf
4: In max(x) : no non-missing arguments to max; returning -Inf
Error in hclust(x, method = "complete") :
NA/NaN/Inf in foreign function call (arg 11)
Calls: hclustfunc -> hclust
Execution halted
〜
答案 0 :(得分:5)
错误是由于数据中存在非数字变量(编码为字符串的数字)。 您可以将它们转换为数字:
mydata <- apply( mtcars, 2, as.numeric )
d <- distfunc(mydata)
答案 1 :(得分:3)
在这种情况下使用as.numeric可能有所帮助,但我认为原始问题指向daisy
函数中的错误。具体来说,它具有以下代码:
if (any(ina <- is.na(type3)))
stop(gettextf("invalid type %s for column numbers %s",
type2[ina], pColl(which(is.na))))
未打印预期的错误消息,因为which(is.na)
错误。它应该是which(ina)
。
我想我现在应该找出在哪里/如何提交此错误。