我正在尝试对我创建的函数中的1和0进行计数或求和。但是由于某种原因,它总是返回(null)或integer(0)的类。我做错了什么,有人可以解释一下吗?
set.seed(4233) # set the random seed for reproducibility
vec1 <- sample(x = 0:9, size = 15, replace = TRUE)
vec1
test1 <- function(n){
for (i in n)
if (i %% 2 == 0){
print(1)
} else {
print(0)
}
}
testing <- test1(vec1)
length(which(testing == 1))
答案 0 :(得分:1)
在这里,问题在于函数return
没有任何作用。它只是print
ing价值。相反,我们可以将输出存储在vector
test1 <- function(n){
v1 <- numeric(length(n)) # initialize a vector of 0s to store the output
for (i in seq_along(n)) { # loop through the sequence of vector
if (n[i] %% 2 == 0){
v1[i] <- 1 # replace each element of v1 based on the condition
} else {
v1[i] <- 0
}
}
v1 # return the vector
}
test1(vec1)
#[1] 1 0 0 0 0 0 0 0 0 0 0 1 1 0 1
请注意,这不需要任何for
循环
as.integer(!vec1 %%2)
#[1] 1 0 0 0 0 0 0 0 0 0 0 1 1 0 1