2014-11-18 4 views
1

데이터 프레임이 있고 각 열에 대한 최대 값이 같은 행에 있도록 각 열을 '정렬'하고 싶습니다.R 이동 벡터

기본 기능을 사용하여이 작업을 수행하려고했지만 잘못된 결과가 나타납니다. 그냥 겹쳐 쓰고 움직이지 마라. 나는 Hmisc의 Lag 함수를 발견했다. 그러나베이스에서이 작업을 수행 할 수있는 방법이 있다고 확신한다. 나는 잘못 생각하고있다. 나중에 이것을 다른 컴퓨터에서 R의 다른적인 버전 항상 지원하지 않는 일부 패키지가 어떤 도움

감사합니다,

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 
}) 
+0

한 줄로 작성해야하지만 답변이 정확한지 확인하려면 샘플 데이터를 게시하고 출력 할 수 있습니까? – John

+0

@beginneR 코드가 그렇게 작동하지 않습니다. 시도 해봐. – nograpes

+0

@nograpes - 네 말이 맞아. 다시 한 번'dplyr :: lag'을'stats :: lag'와 혼동했습니다. –

답변

1

난 당신이 한 줄에 오타가 생각한다.

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

(length(x)-shift)을 확인하십시오. +은여야합니다.주변에 대괄호가 있어야합니다.


코드를보다 간결 버전이 될 것이지만 :

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) 
+0

'base :: lag'는 시계열 객체를 반환합니다. – nograpes

5

시프트 기능 구현/같이해야 할 것에 대한 나의 해석 :

#' function that shifts vector values to right or left 
#' 
#' @param x Vector for ehich to shift values 
#' @param n Number of places to be shifted. 
#' Positive numbers will shift to the right by default. 
#' Negative numbers will shift to the left by default. 
#' The direction can be inverted by the invert parameter. 
#' @param invert Whether or not the default shift directions 
#' should be inverted. 
#' @param default The value that should be inserted by default. 

shift <- function(x, n, invert=FALSE, default=NA){ 
    stopifnot(length(x)>=n) 
    if(n==0){ 
    return(x) 
    } 
    n <- ifelse(invert, n*(-1), n) 
    if(n<0){ 
    n <- abs(n) 
    forward=FALSE 
    }else{ 
    forward=TRUE 
    } 
    if(forward){ 
    return(c(rep(default, n), x[seq_len(length(x)-n)])) 
    } 
    if(!forward){ 
    return(c(x[seq_len(length(x)-n)+n], rep(default, n))) 
    } 
} 

사용 예제

shift(1:10, 5) 
## [1] NA NA NA NA NA 1 2 3 4 5 

shift(1:10, -5, default = 999) 
## [1] 6 7 8 9 10 999 999 999 999 999 
+0

감사합니다. 그것은 나를 위해 일한다. – andrii