I have this function in R from a previous question here
shift <- function(d, k) rbind( tail(d,k), head(d,-k), deparse.level = 0 )
this function will rotate the data frame d by K, that’s mean it will take K rows from the end of the data frame and place them on the top.
I want to create the same function(in the same language) but without using R pre-made functions(head, tail,…), but only using basics of programming.(for , …)
How this can be done?
Well I don’t know what you mean with
without using R functionssince pretty much everything is an R function, but here is a solution using only the very genericnrow()(Number of rows of a matrix),%%(modulus) andseq_len(equivalent to1:length(x)except that it works better):If you mean with “normal programming code” that it shouldn’t be vectorized then, well, you are learning either the wrong language in the right way or the right language in the wrong way. Everytime you come up with a vectorized solution instead of
forloops you are happy in R.But if you really really want to do this with loops here is exactly the same function unvectorized:
Proof they are all equal:
EDIT:
Actually
shift3()there STILL contained a lot of vectorizations, showing just how native that is in R. Here is a fully unvectorized version: