Search code examples
r

Shifting a vector


I have a data frame and I would like to 'align' each column so that the maximum value for each column is on the same row.

I was trying to do this using base functionality, but am getting the wrong results, ie. just overwriting and not shifting. I just found the Lag function in Hmisc, however, I am sure there is a way to do this in base and I"m just thinking about it wrong. I would prefer this, as when I try to run this later on another computer with a different verison of R there are always some package that aren't supported.

Thanks for any help,

maxIndices<-apply(df,2,function(x){
maxInt<-max(x,na.rm=T)
maxInt_indx<-which(x==maxInt) 
})
maxMaxIndex<-max(maxIndices)
minMaxIndex<-min(maxIndices)
##
apply(df,2,function(x){
  maxInt<-max(x,na.rm=T)
  maxInt_indx<-which(x==maxInt)
 shift<-maxMaxIndex-maxInt_indx
shifted_vec<-c(rep(NA,times=shift), x[1:length(x)+shift]) ## this is producing the wrong results
# shifted_vec<-Lag(x,shift) # is there a way to do this using just base functionality
})

Solution

  • I think you just have a typo in one line:

      shifted_vec<-c(rep(NA,times=shift), x[1:(length(x)-shift)]) ## this is producing the wrong results
    

    Notice the (length(x)-shift). The + should be a - and there should be brackets around it.


    Although a more concise version of your code would be:

    max.ind <- sapply(df, which.max)
    diff <- max(max.ind) - max.ind
    shift <- function (x, shift) c(rep(NA,times=shift), x[1:(length(x)-shift)])
    mapply(shift, df, diff)