The condition has length > 1 and only the first element will be used. What changes to make?

后端 未结 2 1170
夕颜
夕颜 2020-12-07 06:12

When i run the below function, i get the output for just one value. with a message, \"the condition has length > 1 and only the first element will be used\"

What cha

2条回答
  •  既然无缘
    2020-12-07 06:20

    The other way to vectorize this function is to use ifelse instead of if:

    ownsquare2 <- function(n)
    {
        for (i in seq(from = 1, to = 506, by = 0.001))
        {
            r <- i * i
            x <- ifelse(r <= n, i, x)
        }
        x 
    }
    ownsquare2(1:10)
    ## [1] 1.000 1.414 1.732 2.000 2.236 2.449 2.645 2.828 3.000 3.162
    

    Here, x is treated as a vector in the function, and the substitution used in the if expression is vectorized with ifelse.

    The translation from if to ifelse is fairly straightforward, but becomes unreadable (IMO) for chained if-else code.

提交回复
热议问题