转移向量

用户名

我有一个数据框,我想“对齐”每一列,以便每一列的最大值在同一行上。

我试图使用基本功能来执行此操作,但是得到了错误的结果,即。只是覆盖而不是转移。我刚刚在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
})
Nograpes

我想您只是在一行中有错别字:

  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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章