如何在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中的错误("重新定位"(:没有适用于"重新定位"类对象的方法;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())

最新更新