# Writing a Mathematical function for a vector of numbers

I am 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?

Tagged:

## Comments

Your res-vector is initialized with zeros.

You can see that with:

vector(mode = "numeric", length = length(c(0.5, 0.6)))

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]

In R you can do calculations on vectors like that

x <- c(0.5, 0.6) (1-x)^2

so you don't need a for-loop here.