Reputation: 11
I'm writing a function that should calculate the following of a vector of numbers (1 - x)^2. However, my function returns zeros and I don't know why:
ban <- function(x){
res <- vector(mode = "numeric", length(x))
for(i in x)
{ res[i] <- (1 - res[i])^2}
return(res)
}
input: ban(c(0.5, 0.6))
gives output: [1] 0 0
. Why is the output zeros?
Upvotes: 0
Views: 850
Reputation: 7724
Your res
-vector is initialized with zeros. You can see that with:
vector(mode = "numeric", length = length(c(0.5, 0.6)))
# [1] 0 0
Further in your for
-loop you loop over x
and use this to access the entries in res
. But your x
-vector contains non-integer values so the access does not work:
res <- c(1, 2)
res[0.5]
# numeric(0)
In R
you can do calculations on vectors like that
x <- c(0.5, 0.6)
(1-x)^2
# [1] 0.25 0.16
so you don't need a for-loop here.
Upvotes: 2