【问题标题】:Can't seem to get function to work, integer(0)似乎无法使功能正常工作,整数(0)
【发布时间】:2026-02-01 15:50:01
【问题描述】:

我正在尝试计算或求和我创建的函数中 1 和 0 的数量。但由于某种原因,它一直返回一个类(null)或一个整数(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))

【问题讨论】:

  • 没问题。我发布了一个返回输出的解决方案

标签: r function null


【解决方案1】:

这里的问题是函数returns 什么都没有。这只是printing 值。相反,我们可以将输出存储在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

【讨论】: