How can I create a function that accepts as an argument an n- dimensional vector that will return (x1, x2^2, ..., xn^n)
in R.
Asked
Active
Viewed 81 times
0

jpsmith
- 11,023
- 5
- 15
- 36
-
1Welcome! To get good help fast on this site, it would be best if you edited your question to provide some sample data, some sample code, and an example of your desired output. Good luck! – jpsmith Jan 12 '23 at 14:12
-
2`f <- function(x) x^seq_along(x)` defines such a function, but what do you mean by "as well as the numbers from 1 to 7"? That is just `1:7`. Surely you don't want a function on vectors which for no apparent reason returns `1:7` as well. – John Coleman Jan 12 '23 at 14:15
-
so what i meant about the numbers from 1 to 7, was for each number separetively the vector to give a number, f.e 1^1 , 2^2, 3^3 etc – Ειρήνη Θεοδωροπούλου Jan 12 '23 at 14:52
1 Answers
2
Do you mean something like this? An extension of @JohnColeman's comment. This will use cbind
to make a 2-dimensional matrix that contains both the n-dimensional input vector and the resulting product.
examplefun <- function(x) {
cbind(seq_along(x), x^seq_along(x))
}
# test function
examplefun(1:7)
# [,1] [,2]
# [1,] 1 1
# [2,] 2 4
# [3,] 3 27
# [4,] 4 256
# [5,] 5 3125
# [6,] 6 46656
# [7,] 7 823543
If you just want the product:
examplefun <- function(x) {
x^seq_along(x)
}
example fun(1:7)
# [1] 1 4 27 256 3125 46656 823543

jpsmith
- 11,023
- 5
- 15
- 36
-
0 no, our prof of statistics doesnt want a matrix, he wants the vector to give us a result of xn^n. For instance, 2^2,3^3,4^4 etc – Ειρήνη Θεοδωροπούλου Jan 12 '23 at 14:46
-
See edit - is this what you want? This is the function in the comment on your question. – jpsmith Jan 12 '23 at 14:49
-
Great! If this answers your question please click the checkmark to close this question out and clean up the site (so folks know this is answered and can spend their time helping others). Again, welcome to SO! – jpsmith Jan 12 '23 at 14:56