我有两个字符子数组如下:
, , 1
[,1] [,2] [,3] [,4] [,5]
[1,] "5" "3" "1" "1" "5"
[2,] "4" "1" "1" "1" "3"
[3,] "5" "5" "4" "5" "1"
[4,] "5" "5" "1" "3" "5"
[5,] "3" "4" "1" "4" "5"
[6,] "2" "5" "4" "5" "2"
[7,] "2" "5" "5" "4" "2"
[8,] "5" "5" "2" "2" "2"
[9,] "2" "5" "4" "5" "4"
[10,] "2" "2" "5" "2" "1"
, , 2
[,1] [,2] [,3] [,4] [,5]
[1,] "2" "2" "2" "4" "5"
[2,] "3" "1" "2" "1" "4"
[3,] "5" "2" "3" "4" "4"
[4,] "3" "3" "4" "5" "3"
[5,] "2" "1" "5" "1" "3"
[6,] "5" "5" "2" "5" "4"
[7,] "1" "5" "1" "3" "4"
[8,] "1" "5" "3" "3" "5"
[9,] "4" "5" "1" "1" "2"
[10,] "5" "1" "2" "3" "5"
现在我编写了一个R例程来从这些数组中的一个中随机采样一行(1或2)。
但我想要做的是从BOTH子阵列中随机抽样并采用列式方法。我可以在不首先从字符转换为数值的情况下完成此操作吗?
因此,如果在1和2中对行1进行采样,则列式均值(适当舍入)将是(未在R中完成)
"(5+2)/2", "(3+2)/2", "(1+2)/2", "(1+4)/2", "(5+5)/2"
= "4", "3", "2", "3", "5"
从一个数组中随机抽样行的我(部分)例程如下。我想为两个数组修改它。
for(k in specs){
for(j in 1:perms){
for(i in 1:K){
ind.index <- sample(specs, size = k, replace = FALSE)
hap.plot <- pop[sample(1:nrow(pop), size = 1, replace = TRUE), ind.index, sample(i, size = 1, replace = TRUE)]
HAC.mat[j, k, i] <- length(unique(hap.plot))
}
}
}
非常感谢任何帮助。
如果需要进一步澄清,请告诉我。
答案 0 :(得分:1)
我们可以使用apply
i1 <- sample(seq_len(dim(ar1)[1]), 2)
apply(ar1[i1,,], c(1, 2), FUN = function(x) mean(as.numeric(x)))
或通过循环第三维
来使用rowMeans
rowMeans(apply(ar1[i1,,], 3, FUN = function(x) as.numeric(x)))
set.seed(24)
ar1 <- array(as.character(sample(1:5, 10*5*2, replace = TRUE)), dim = c(10, 5, 2))
答案 1 :(得分:1)
测试数据
mat <- array(as.character(1:40), c(15, 5, 2))
从每个中分别随机抽样并得到均值。
n_row <- dim(mat)[1]
s_rows <- sample(1:n_row, 2, replace = TRUE)
unlist(lapply(mat[s_rows[1],, 1], as.numeric))/2 +
unlist(lapply(mat[s_rows[2],, 2], as.numeric))/2