如何将几列移动到 R 中数据框的前面?

How to move several columns to front of dataframe in R?

我正在编写一个模拟,我正在尝试多种测试方法。在我的模拟中,我想改变真实零假设的百分比,并将真实零假设移动到我的数据框的开头。当零假设的数量发生变化时,这被证明有点棘手。 我研究过按索引移动它们,但这并不适用于所有情况。 (特别是 h0 = 0) 看起来 relocate() 可能会做我想做的事,但我可以将它用于多个列,并且只使用列索引吗?

我只是在我的模拟中包含了错误发生的“内循环”。首先你可以看到我想要改变 h0 的级别。

iter <- 100 #number of iterations for 1 datapoint
rho_vec <- c(0, 0.20, 0.40, 0.60, 0.80) # correlation value
h0_vec <- c(0, 0.20, 0.40, 0.60, 0.80) # list of percentage of true h0

 for(j in 1 : iter){
      mu11 <- c(rep(0, (h0*50)), rep(1.5, (1-h0)*50)) #vector giving the means of the variables. true nulls have 0 mean, false nulls have 1.5 in mean. (12 false h0)
      Sigma11 <- diag(k) + rho - diag(k)*rho #Making simple correlation matrix for dependent variables
      corrdata1 <- mvrnorm(n, mu = mu11, Sigma = Sigma11) 
      
      # now we simulate the unncorrelated data with (1-h0)*50) non-true null hypothesis. n and k are the same.
      mu12 <- c(rep(0, h0*50), rep(1.5, (1-h0)*50))
      SigmaId <- diag(k) #making correlation matrix (id matrix) for independent data.
      indepdata1 <- mvrnorm(n, mu = mu12, Sigma = SigmaId)
      
      #we define the total data matrix for both of the cases
      data1 <- cbind(corrdata1,indepdata1) #a 100 x 1000 matrix with 1000 observations of 100 variables
      
      #reorder columns so the false nulls are the last columns.

      #data1 <- data1[, c( 0:(h0*50), 51:(50+(h0*50)), (51-((1-h0)*50)):50, (101-(50*(1-h0))):100)] #can check this by calling colMeans(data1). I tried this version first.

      data1 %>% relocate(c(0:(h0*50), 51:(50 + (h0*50))) %>% head()) # this is the relocate() approach.

}

这会在 relocate() 中产生错误: “UseMethod(“重新定位”)中的错误: 没有适用于 'relocate' 的适用方法应用于 class 的对象“c('matrix', 'double', 'numeric')” 有没有人对如何做到这一点有任何想法?非常感谢您的建议!

错误消息告诉您 relocate() 已应用于 matrix 对象,但它不能这样做。事实上,relocate() 必须应用于数据框,因此您应该事先使用 as.data.frame()as_tibble(),如评论中所述。

最后,使用函数后要对结果重新赋值,否则不会有任何效果:

data1 <- data1 %>% as_tibble() %>% relocate(c(0:(h0*50), 51:(50 + (h0*50))) %>% head())