jeudi 1 octobre 2020

Sample from a dataframe with specified probabilities in R

Below, I first group my data.frame (d) by a 5-level categorical variable called sector (Education, Industry, NGO, Private, Public). Then, I want to sample from each level of sector with the following probabilities: c(.2, .3, .4, .1).

I'm using the code below to achieve my goal without success? Is there a fix for that?

library(tidyverse)

d <- read.csv('https://raw.githubusercontent.com/rnorouzian/d/master/su.csv')

set.seed(1)
(out <- d %>%
  group_by(sector) %>%
  slice_sample(n = 2, weight_by = c(.2, .3, .4, .1))) # `Error: incorrect number of probabilities`



how to iterate over random range in python and count results

I am new to programming and I am trying to create a random number iterator that will take in a numpy random range and count how many times each individual number from 1-10 appears.

Example: random range goes from 1 to 5 and it will count how many times the #s appear. count1 appears once, count2 appears 3 times and count 9 appears once.

code:

import numpy as np

x1 = np.random.random(10)


count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0 
count10 = 0

for x in range(1,x1): 
  if x == 1:
    count1 += count1
  elif x == 2:
    count2 += count2
  elif x == 3:
    count3 += count3
  elif x == 4:
    count4 += count4
  elif x == 5:
    count5 += count5
  elif x == 6:
    count6 += count6
  elif x == 7:
    count7 += count7
  elif x == 8:
    count8 += count8
  elif x == 9:
    count9 += count9
  elif x == 10:
    count10 += count10
    
    print(count1)
    print(count2)
    print(count3)
    print(count4)
    print(count5)
    print(count6)
    print(count7)
    print(count8)
    print(count9)
    print(count10)

    
    
    
    
    
    



JS get random value from array and update array

I need your help on this! I'm generating an array which corresponds to a question number.

var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}

then I use this number to append the corresponding question, answer then click. Then I'm getting a new value from the array like this

const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);

It works and a new question is charged but the array is still the same. I've tried this

var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);

But It doesn't work ;-(

Thanks a lot for your help. Nicolas

Here is the entire code to help comprehension! sorry for that, I should have done it from the begining.

<!DOCTYPE HTML>
<!--
    Hyperspace by HTML5 UP
    html5up.net | @ajlkn
    Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>

<head>
    <title>Repérez vos messages contraignants - Quiz</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="assets/css/main.css" />
    <noscript>
        <link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>

<body class="is-preload">
    <!-- Sidebar -->
    <!-- <section id="sidebar">
    </section> -->
    <!-- Wrapper -->
    <div id="wrapper">
        <!-- Intro -->
        <section id="intro" class="wrapper style1 fullscreen fade-up">
            <div class="inner">
                <header>
                    <button id="start">Commencer</button>
                    <p>&nbsp;</p>
                </header>
                <form action="" method="post">
                    <p id="Qnum"></p>
                    <p id="Q" data-qnumber="" data-type=""></p>
                    <section id="answer">
                        <input type="submit" id="1" name="R1" value="Non">
                        <input type="submit" id="2" name="R2" value="Parfois">
                        <input type="submit" id="3" name="R3" value="Souvent">
                        <input type="submit" id="4" name="R4" value="Oui">
                    </section>
                </form>
            </div>
        </section>
        <!-- Footer -->
        <!-- Scripts -->
        <script src="assets/js/jquery.min.js"></script>
        <script src="assets/js/jquery.scrollex.min.js"></script>
        <script src="assets/js/jquery.scrolly.min.js"></script>
        <script src="assets/js/browser.min.js"></script>
        <script src="assets/js/breakpoints.min.js"></script>
        <script src="assets/js/util.js"></script>
        <script src="assets/js/main.js"></script>
        <script>
        $(document).ready(function() {

            if (localStorage.getItem("clic") >= 45) {
                console.log('45');
                sessionStorage.clear();
                localStorage.clear();
            }

            var Q1 = [1, "My first question", "FP"];
            var Q2 = [2, "My second question", "SP"];
            var Q3 = [3, "My third question", "SE"];
            var Q4 = [4, "My foutrh question", "DP"];
            var Q5 = [5, "My fifth question", "FP"];    
            //etc... until Q45


            if (sessionStorage.getItem("FP") == null) {

                $("form").attr("action", "driversV2.php");
                $("#answer").hide();
                $("#start").click(function() {

                    $("#Qnum").append(1+" / 45");
                    $("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
                    $("#answer").show();
                    $("header").hide();

                    var pageType = $("#Q").attr("data-type");
                    $("input").click(function() {
                        var reponse = this.id;
                        sessionStorage.setItem(pageType, reponse);
                        localStorage.setItem("clic", 1);
                    });
                });

            } else {
                $("header").hide();
                var clicNum = parseInt(localStorage.getItem("clic"));
                var QNumber = clicNum + 1;
                var arrayCharge = [];
                for (var i = 2; i <= 45; i++) {
                  arrayCharge.push(i);
                }
                const randomQ = arrayChargeNew;
                const random = Math.floor(Math.random() * randomQ.length);
                console.log('valeur random new = '+randomQ[random]);
                var QCharge = "Q" + randomQ[random];
                var Charge = eval(QCharge);
                localStorage.setItem("random",randomQ[random]);
   
                $("#Qnum").append(QNumber+" / 45");
                $("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
                //création de la variable du type de question
                var pageType = $("#Q").attr("data-type");
                //alert(sessionStorage.getItem(pageType));
                if (localStorage.getItem("clic") < 44) {

                    $("form").attr("action", "driversV2.php");

                    if (sessionStorage.getItem(pageType) != null) {
                        var x = parseInt(sessionStorage.getItem(pageType));
                        $("input").click(function() {
                            var reponse = parseInt(this.id);
                            var addition = reponse + x;
                            sessionStorage.setItem(pageType, addition);
                            var clic = parseInt(localStorage.getItem("clic"));
                            localStorage.setItem("clic", clic + 1);
                        });
                    } else {
                        $("input").click(function() {
                            var reponse = this.id;
                            sessionStorage.setItem(pageType, reponse);
                            var clic = parseInt(localStorage.getItem("clic"));
                            localStorage.setItem("clic", clic + 1);

                        });
                    }
                } else {
                    $("form").attr("action", "driversResultat.php");

                    if (sessionStorage.getItem(pageType) != null) {
                        var x = parseInt(sessionStorage.getItem(pageType));
                        $("input").click(function() {
                            var reponse = parseInt(this.id);
                            var addition = reponse + x;
                            sessionStorage.setItem(pageType, addition);
                            var clic = parseInt(localStorage.getItem("clic"));
                            localStorage.setItem("clic", clic + 1);

                        });
                    } else {
                        $("input").click(function() {
                            var reponse = this.id;
                            sessionStorage.setItem(pageType, reponse);
                            var clic = parseInt(localStorage.getItem("clic"));
                            localStorage.setItem("clic", clic + 1);

                        });
                    }
                }
            }
        });
        </script>
</body>

</html>



Google Sheets Script - How to select a random selection of cells according to a predefined set of rules

Hey guys I'm a beginner in Google Apps Script and I'm having trouble writing a script.

Here's my problem : I have a sheet B with with a list of 77 companies, their employee count and their size ("very small, small, medium, big") and I would like to select a random selection of companies according to a predefined set of rules, and display them in sheet A. (here's my sheet)

For example, I'd like to select 2 very small companies, 3 small companies, 4 medium companies, and 1 big company every time I click on a button.

When I click on the button, I'd like the list to reset and select new companies.

Here's my code so far , but I have trouble figuring out to complete it :

var companyList = Spreadsheet.getSheetByName("Company List");
var lastrow = getLastPopulatedRow(companyList);
var dataCompanyList = companyList.getDataRange().getValues();

var verysmall = 0;
var small = 0;
var medium = 0;
var big = 0;

var verysmallAlternate = 0;
var smallAlternate = 0;
var mediumAlternate = 0;
var bigAlternate = 0;

var breakLoop = 90000;
var companyList = []; 

function gethashtags() {
  
  while (verysmall<2)
  {
    randomNum = Math.floor(Math.random() * (77));
    if (dataCompanyList[randomNum][2] == "verysmall")

{ 
company = dataCompanyList[randomNum][0];
verysmall++;
companyList.push(dataCompanyList[randomNum][0]);
}

{
verysmallAlternate++;
if(verysmallAlternate>breakLoop) {
verysmall;
}

while (small<3)
  {
    randomNum = Math.floor(Math.random() * (77));
    if (dataCompanyList[randomNum][2] == "verysmall")

{ 
company = dataCompanyList[randomNum][0];
small++;
companyList.push(dataCompanyList[randomNum][0]);
}

{
smallAlternate++;
if(smallAlternate>breakLoop) {
small++;
}

while (medium<4)
  {
    randomNum = Math.floor(Math.random() * (77));
    if (dataCompanyList[randomNum][2] == "medium")

{ 
company = dataCompanyList[randomNum][0];
medium++;
companyList.push(dataCompanyList[randomNum][0]);
}

{
mediumAlternate++;
if(mediumAlternate>breakLoop) {
medium++;
}

while (big<1)
  {
    randomNum = Math.floor(Math.random() * (77));
    if (dataCompanyList[randomNum][2] == "big")

{ 
company = dataCompanyList[randomNum][0];
big++;
companyList.push(dataCompanyList[randomNum][0]);
}

{
bigAlternate++;
if(bigAlternate>breakLoop) {
big++;
}
}

What I can't figure out is how to make this work and display the companyList Array in the cell in the sheet A.




Artificial dataset for collaborative filtering

I am trying to achieve an artificial dataset for a generic collaborative filtering model.

For simplicities sake, we can assume that it is a model for users and movies and the ratings each user gives a movie.

For generating the data, I did the following:

1. Give each user a random different value from 5 to 20.
2. All movies such that {movie_index % user_value == 0} were 'liked' by that particular user, \
ones with {movie_index % user_value == ±1} were 'disliked' and rest were 'neutral'.
    > For a user with value 12, movie with the index 12 and 24 would be liked, and 13 would be disliked.
3. For actually assigning the ratings to movies, I used the following code:
   if (movie.LikedBy(user)) then rating = np.random.normal(4,0.5)
   elif (movie.DislikedBy(user)) then rating = np.random.normal(1,0.5)
   else rating = np.random.normal(2.5,1)

The problems I'm facing is that the model is too eager to learn 2.5 as the suggested rating, and even in the data it's not uncommon to see 'liked' movies to be given a rating of 1...which I feel may be generating way too many outliers in our dataset.

Is there a better way to generate this data or is it better to just use an already existing dataset for movie ratings?




mercredi 30 septembre 2020

Random float number for different scenarios

Is it possible to generate a random float number that is (a,b],(a,b)? for example, (0,100], it will never be 0, but it can be 100.




How to cast random numbers in an array?

I'm currently trying to create 20 random numbers in an array and set these values to either 0 or 1. The problem I'm having after this is when I try to do a bit of casting to try and get these numbers to doubles. From what I understand (Not much), this should work, but it just outputs 0's and 1's again. I'd really appreciate any help or advice, or even any links to tutorials that might help! Thank you in advance!

#include <iostream>

using namespace std;

int main()
{
   int array[20] = { 0 };

   for (int j = 0; j < 20; j++)
   {
      array[j] = rand() % 2;

      cout << (double)array[j] << endl;
  }

}