$运算符对于for循环内的原子向量无效
我使用的算法如下所示:$运算符对于for循环内的原子向量无效,r,R,我使用的算法如下所示: 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:
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)
}
df你在找这样的东西吗
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
f可能你正在经历的是。不过我应该注意,这只是一个猜测,因为你的例子是不可复制的。这不仅是不可复制的,您甚至没有提供错误具体发生在哪里的信息。我将其标记为问题joran linked的重复,这应该有一个很好的答案来解释为什么会发生这种情况。虽然我认为重构代码时最好不要使用for循环(我不是100%确定这是必要的)。那么你建议用什么来代替for循环呢?具体来说:df[I,1:dim,drop=FALSE]