我有一个数据框,我想'对齐'每列,以便每列的最大值在同一行.
我试图使用基本功能来做到这一点,但是得到了错误的结果,即.只是覆盖而不是转移.我刚刚在Hmisc中找到了Lag函数,但是,我确信在base中有一种方法可以做到这一点我只是想错了.我更喜欢这个,就像我以后尝试在另一台计算机上运行它一样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
})
Run Code Online (Sandbox Code Playgroud)
我对shift函数实现可能/应该是什么样的解释:
#' 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)))
}
}
Run Code Online (Sandbox Code Playgroud)
示例用法
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9509 次 |
| 最近记录: |