在R中,计算平均从1000次重复

时间:2018-04-22 18:16:08

标签: r replicate

我试图进行1000次测试,总结所有答案并将其全部除以1000.

我正在尝试这样的事情,但它不起作用,但它只给了我一次这样做的价值。

(array_1 ==1 and array_2 ==1) = 0
(array_1 ==1 and array_2 ==2) = 10 
(array_1 ==1 and array_2 ==3) = 15
(array_1 ==2 and array_2 ==1) = 5
(array_1 ==2 and array_2 ==2) = 0
(array_1 ==2 and array_2 ==3) = 15
(array_1 ==3 and array_2 ==1) = 5
(array_1 ==3 and array_2 ==2) = 10
(array_1 ==3 and array_3 ==3) = 0

2 个答案:

答案 0 :(得分:3)

这是一个更加R - ish解决方案,它不使用循环:

x <- replicate(1000, sample.int(500,30,replace=F))
y <- abs(2*colMeans(x)-501)

sumValue = sum(y)
divValue = mean(y)

replicate将为我们提供所需的输出作为矩阵,然后我们可以使用向量化函数colMeans

随着重复次数的增加,此方法的效果会更好:

loopSoln <- function(N) {
  value = list()
  for(i in 1:N) {
    x=sample(1:500,30,replace=F)
    mhat=stimateM=2*mean(x)-1
    y=abs(mhat-500)
    value[i]=y
  }
  sumValue = sum(unlist(value))
  divValue = sumValue/N
}

replicateSoln <- function(N) {
  x <- replicate(1000, sample.int(500,30,replace=F))
  y <- abs(2*colMeans(x)-501)
  sumValue = sum(y)
  divValue = mean(y)
}

(ltimes <- sapply(c(1e2,1e3,1e4,1e5), function(N) system.time(loopSoln(N))[3]))
## elapsed elapsed elapsed elapsed 
##   0.002   0.014   0.158   2.009 

(rtimes <- sapply(c(1e2,1e3,1e4,1e5), function(N) system.time(replicateSoln(N))[3]))
## elapsed elapsed elapsed elapsed 
##   0.007   0.011   0.007   0.010 

plot(ltimes~I(2:5), type = 'l', col = 2, xlab = "log_10 number of replicates", ylab = "elapsed time (sec)")
lines(rtimes~I(2:5), col = 4)
legend("topleft", lty = 1, col = c(2,4), 
  legend = c("Loop", "replicate + rowMeans"))

Benchmarks

答案 1 :(得分:0)

为了建立coffeinjunky的建议,下面是一个在循环外定义容器,然后在循环内添加模拟值,然后在循环外对所有值进行求和和除法的示例。

public class Solution9 {
public static void main(String[] args) {
    String a = "Gini Gina Protijayi";


       System.out.println(   urlencode(a));
}//main

public static String urlencode(String str) {
      str = str.trim();
        System.out.println("trim =>" + str);

        if (!str.contains(" ")) {
            return str;
        }

    char[] ca = str.toCharArray();

    int spaces = 0;
    for (char c : ca) {
        if (c == ' ') {
            spaces++;
        }
    }

    char[] newca = new char[ca.length + 2 * spaces];
      //  a pointer x has been added
    for (int i = 0, x = 0; i < ca.length; i++) {
        char c = ca[i];
        if (c == ' ') {
            newca[x] = '%';
            newca[x + 1] = '2';
            newca[x + 2] = '0';
            x += 3;
        } else {
            newca[x] = c;
            x++;
        }
    }
    return new String(newca);
}

}//urlify