我使用的算法如下:
df <- read.table(sep=" ", header=T, text="
x y z label
1 3 2 a
2 4 4 b
3 8 5 c
4 5 6 a
5 1 8 f")
f <- function(refObs, label) {
d <- vector()
for (i in which(df$label==label))
d <- c(d, dist(rbind (refObs, df[i,1:dim]) , method ="euclidean") )
return(dist)
}
问题是当我用dim = 1调用这个函数时,我有时会得到“$ operator对原子向量无效”。有没有办法从数据帧中调用不会让我失望的列?更具体一点:我可以调用f函数分配空标签吗?
答案 0 :(得分:0)
你在找这样的东西吗?
f <- function(df, refObs, label=NULL) {
df <- as.data.frame(df)
d <- vector()
if (is.null(label) | !"label" %in% names(df)) {
rows <- 1:nrow(df)
} else
rows <- which(df$label==label)
if (length(refObs) != length(which(names(df) != "label")))
stop("refObs too short or too long")
for (i in rows)
d <- c(d, dist(rbind(refObs, df[i,1:length(refObs)]), method ="euclidean"))
return(d)
}
f(df, c(1,3,2), "a")
# [1] 0.000000 5.385165
f(df, c(1,3,2))
# [1] 0.000000 2.449490 6.164414 5.385165 7.483315
df <- df[,1]
f(df, 1)
# [1] 0 1 2 3 4