使用for循环来模拟is

  • 本文关键字:模拟 is 循环 for 使用 r
  • 更新时间 :
  • 英文 :


写一个R程序来模拟内置的R函数是。元素(x, y)的两个向量x和y。换句话说,您的程序返回与x长度相同的向量答案,并且当且仅当x[i]是y的元素时,answer[i]为TRUE。不要使用任何R的内置函数,例如is.element()或%中的%.

这是我的代码:(但它不返回一个向量)

x <- c(3, 0, -2, 0)
y <- c(-1, 0, 1)
n <- length(x)
answer <- logical(n)
for (i in 1:n){
if (x[i]) {
answer <- TRUE
}
else {
answer <- FALSE
}

}
answer

您需要在循环中更改answer[i]。尝试——

x <- c(3, 0, -2, 0)
y <- c(-1, 0, 1)
n <- length(x)
answer <- logical(n)
for (i in 1:n){
answer[i] <- any(x[i] == y)
}
answer
#[1] FALSE  TRUE FALSE  TRUE

如果不允许使用any,您也可以对xy中的每个值使用双环。

x <- c(3, 0, -2, 0)
y <- c(-1, 0, 1)
n <- length(x)
answer <- logical(n)
for (i in seq_along(x)){
tmp <- FALSE
for(j in seq_along(y)) {
tmp <- tmp | x[i] == y[j]
}
answer[i] <- tmp
}
answer

相关内容

最新更新