组内的随机播放矢量,保留顺序

时间:2018-03-30 01:55:25

标签: r permutation shuffle

我有一个矢量:

x = c(1, 2, 3, 4, 5)
g = c('a', 'b', 'a', 'b', 'b')

还有一些团体:

shuffled_x = c(3, 5, 1, 4, 2)
shuffled_g = c('a', 'b', 'a', 'b', 'b')

我想要改组每个组中的向量元素,但保留原始组排序。例如:

shuffled_x = c(3, 1, 4, 5, 2)
shuffled_g = c('a', 'a', 'b', 'b', 'b')

好的解决方案:

y = tapply(x, g, sample)

糟糕的解决方案:

function upload(fileInputId, fileIndex)
    {
        var file = document.getElementById(fileInputId).files[fileIndex];
        var blob;
        var reader = new FileReader();
        reader.readAsBinaryString(file); 
        reader.onloadend  = function(evt)
        {
            xhr = new XMLHttpRequest();

            xhr.open("POST", 'upload.php?name=' + file.name, true);

            XMLHttpRequest.prototype.mySendAsBinary = function(text){
                var data = new ArrayBuffer(text.length);
                var ui8a = new Uint8Array(data, 0);
                for (var i = 0; i < text.length; i++){ 
                    ui8a[i] = (text.charCodeAt(i) & 0xff);

                }

                if(typeof window.Blob == "function")
                {
                     blob = new Blob([data]);
                }else{
                     var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
                     bb.append(data);
                     blob = bb.getBlob();
                }

                this.send(blob);
            }

            var eventSource = xhr.upload || xhr;
            eventSource.addEventListener("progress", function(e) {
                var position = e.position || e.loaded;
                var total = e.totalSize || e.total;
                var percentage = Math.round((position/total)*100);
            });

            xhr.onreadystatechange = function()
            {
                if(xhr.readyState == 4)
                {
                    if(xhr.status == 200)
                    {
                        console.log("Done");
                    }else{
                        console.log("Fail");
                    }
                }


            };

            xhr.mySendAsBinary(evt.target.result);
        };
    }

我已经知道如何在小组中洗牌:

$inputHandler = fopen('php://input', "r");
$loc = "uploads/" . $_GET["name"];
$fileHandler = fopen($loc, "w+");

while(true) {
    $buffer = fgets($inputHandler, 4096);



    if (strlen($buffer) == 0) {
        fclose($inputHandler);
        fclose($fileHandler);
        return true;
    }

    fwrite($fileHandler, $buffer);
}

不确定如何按正确顺序保存它们。

1 个答案:

答案 0 :(得分:3)

我认为ave会在维护群组的元素之间进行混乱:

ave(x, g, FUN = sample)
#[1] 1 4 3 5 2

ave(x, g, FUN = sample)
#[1] 3 4 1 2 5

ave(x, g, FUN = sample)
#[1] 3 2 1 4 5