简体   繁体   English

在R中创建函数但获得替换的长度为零错误

[英]Creating a function in R but getting a replacement has length zero error

I tried to create a function f and create the function so when a value x is inserted, it spits out a function f from y.But, when I try to run the code to plot, it gives me an error that says that my y_value has no length. 我试图创建一个函数f并创建该函数,所以当插入值x时,它会从y吐出函数f。但是,当我尝试运行代码进行绘图时,它给我一个错误,指出我的y_value没有长度。

f <- function(x){
  if (x<0){
   print(y_values<-x*x*x)
  }
  if(x>0 & x<=1){
    print(y_values<-x*x)
  }
  if(x>1){
    print(y_values<-sqrt(x))
  }

}


x_values <- seq(-2, 2, by = 0.1)
y_values <- rep(NA, length(x_values))
for (i in seq_along(x_values)) {
  x <- x_values[i]
  y_values[i] <- f(x)
}

# output
plot(x_values, y_values, type = "l")

Two issues: 两个问题:

  1. From ?print ?print

    'print' prints its argument and returns it invisibly (via 'invisible(x)') 'print'打印其参数并隐式返回(通过'invisible(x)')

    So all your function f does is print the values to the console (instead of returning them). 因此,函数f所做的所有事情就是将值打印到控制台(而不是返回值)。

  2. As per your definition of f , the function does not know how to deal with x=0 ; 根据您对f的定义,该函数不知道如何处理x=0 so this will create a problem when you store the output of f(0) later. 因此,当您以后存储f(0)的输出时,这将产生问题。

We can fix these issues by slightly altering f as 我们可以通过稍微更改f为解决这些问题

    f <- function(x) {
      y_values <- NA
      if (x<0){
       y_values<-x*x*x
      }
      if(x>0 & x<=1){
        y_values<-x*x
      }
      if(x>1){
        y_values<-sqrt(x)
      }
      return(y_values)
  }

Then 然后

x_values <- seq(-2, 2, by = 0.1)
y_values <- rep(NA, length(x_values))
for (i in seq_along(x_values)) {
  x <- x_values[i]
  y_values[i] <- f(x)
}

plot(x_values, y_values, type = "l")

在此处输入图片说明


You could also use Vectorize to obtain a vectorised function f2 , which allows you to pass x_values as a vector, thereby avoiding the explicit for loop: 您还可以使用Vectorize获得向量化函数f2 ,该函数可以将x_values作为向量传递,从而避免显式的for循环:

f2 <- Vectorize(f)
x_values <- seq(-2, 2, by = 0.1)
y_values <- f2(x_values)

The resulting plot is the same. 结果图是相同的。

I would recommend you explore other methods for coding something like this: 我建议您探索其他编码方法,例如:

here is one option that doesn't use a for loop. 这是一个不使用for循环的选项。 If you are simply working on using for loops then the fix Mauritus Evers made should work for you. 如果您只是在使用for循环,那么Mauritus Evers所做的修复应该适合您。

library(tidyverse)

data.frame(x_values = seq(-2, 2, by = 0.1)) %>% 
  mutate(y_values = case_when(x_values < 0 ~ x_values^3,
                              x_values>=0 & x_values<=1 ~ x_values^2,
                              x_values>1 ~ sqrt(x_values))) %>% 
  ggplot(aes(x_values, y_values)) + geom_point()

note that I changed your code to produce output when x_value = 0. 请注意,当x_value = 0时,我更改了代码以产生输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM