Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205372

Write a function to calculate the square of the first k elements of a vector

$
0
0

I am trying to calculate the square of the first k elements of a vector v.

If k is greater than the length of the vector n, then set k = n.

myfun1 = function(v,k){ 
   p = ifelse(k > length(v), k = length(v), v[1:k]^2)
   return(p)
}

myfun1(v=seq(1,20,by=0.5), k=10)

When I run the code it gives me this error:

Error in ifelse(k > length(v), k = length(v), v[1:k]^2) : unused argument (k = length(v))

Can anyone help to resolve this?


Viewing all articles
Browse latest Browse all 205372

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>