Reputation: 1
I have a vector "I" which we can take for example to be (0,1,2,3.....) till an unknown length. I want to create a vector such that x^(I-1) so it will be a vector that looks like (0,x,x^2...). However I do not know how to write this code and I tried (x^I-1) alone doesn't work.
Upvotes: 0
Views: 413
Reputation: 1928
EDIT*** Read r2evan's comments to understand why this is not a recommended solution.
This will take vector z and feed it it into the function to create the resulting vector. Simply adjust your x value (in this case, the 2)
z <- c(1:5)
new_vector <- sapply(z, function(y) 2 ^ y)
The output values in the new vector then would be x^0, x^1, x^2, x^3... etc.
Upvotes: 0
Reputation: 101099
You can use seq(l)
to construct a l
-length vector from 1
to l
as powers. Since you are pursuing a start from 0
, so you can use seq(l)-1
.
Then, you choose a value of x
, and generate the desired vector via
x**(seq(l)-1)
If you have x
and l
as variables, you can define your custom sequence generator like below
vgen <- function(x,l) x**(seq(l)-1)
and use it like
> vgen(3,7)
[1] 1 3 9 27 81 243 729
Upvotes: 0
Reputation: 8392
As commented on your question, R is vectorized. This means that you can specify a vector y
of integers, a variable x
of length 1, and then take x
to the power of y
via x^y
:
y <- 0:10
x <- 2
x^y
which returns:
[1] 1 2 4 8 16 32 64 128 256 512 1024
Upvotes: 1