Direkt zum Hauptbereich

How to select specific random rows from #MySQL within #R

When you work with big data sets it is a good idea to store everything in a MySQL database. Doing statistics, you often will need a random sample of your data, perhapse from a subpopulation of the data.
The normal way is to run an SQL-querry with the ORDER BY RAND() addition.
Unfortunately, this is slow as hell.
A better way is to load all autoids or rownumbers of the subpopulation first, select a random sample in R and then run a second request where the sample is directly addressed. This is very fast even with huge data sets and has the advantage that you can control the randomness via set.seed.
Here is an example:

require(RMySQL)
# set up RMySQL-connection
con <- dbConnect(RMySQL::MySQL(), host = "myhost",
                 user = "myusername", password = "mypassword",dbname="mydb")
 
# select the auto-ID or Rownumber where the column "col" has the value "select"
IDs <- dbSendQuery(con, "SELECT autoid FROM mytable WHERE col = 'select';")
# fetch the results and set n=-1 to get more than 500 rows
IDs <-dbFetch(myIDs, n=-1)
 
# Set seed for reproduceability
set.seed(12)
# Select sample from IDs (1000 is just an example)
IDs <- IDs[sample(dim(IDs)[1],1000),]
 
# make the second request by collapsing the IDs within a pate-command
res <- dbSendQuery(con, 
                   paste0("SELECT * FROM mytable WHERE col = 'select' AND autoid IN (", 
                          paste(IDs, collapse=","), ")", ";"))
 
# fetch the results
res <-dbFetch(res, n=-1)
 
# close the connection
dbDisconnect(con)



Kommentare

Beliebte Posts aus diesem Blog

#RTutorial: Using R to Harvest the Twitter STREAM API

Initializing the Twitter API In this tutorial, the so called STREAMING-API from Twitter is used. This API provides real-time access to Twitter, so the results are dependent from what is actually going on, right now. Before we start, we have to initialize the Twitter-API. To use the Twitter API, a consumer key and consumer secret is required. Therefore, you have to register as a developer who is creating a Twitter app. Create a Twitter account and then sign in at https://apps.twitter.com/. The account has to be verified with a phone number. This can be done on the Twitter webpage in the account settings. Fill in name, description and any valid URL with leading “http://”. It is important NOT to provide any call-back URL, because otherwise the registration from R will not function. After this, you can see a summary of your newly created app with a link to “manage keys and access tokens”. The consumer key and consumer secret that can be found there have to be copied into the following R-...

Deep-Dive Impfeffektivität: Eine kritische Datenanalyse der RKI-Berechnungen / Teil 1: Die Methode

Die Einschätzung, wie effektiv die COVID-Impfung ist, ist eine der politisch relevantesten Kennzahlen derzeit. Insbesondere für die Einschätzungen der Angemessenheit einr Impfpflicht ist diese Zahl extrem wichtig. In der Vergangenheit hat sich immer wieder gezeigt, dass die Berechnungen des RKI nicht in jeder Hinsicht eindeutig sind, sondern auf vielen Annahmen beruhen, die man auch kritisch hinterfragen kann und muss. Für die politische Datenwissenschaft ist es daher essenziell, diese Berechnungen nachvollziehbar zu machen. In diesem Beitrag wird das methodische Vorgehen des RKI zur Berechnung der Impfeffektivität analysiert. Die Informationen dazu entstammen den RKI-Wochenberichten .  In einem zweiten Teil habe ich die konkreten Berechnungen des RKI so weit wie möglich rekonstruiert und kann daher zeigen, wie stark die Ergebnisse schwanken, wenn Annahmen leicht verändert werden. Meine Erkenntnisse aus der folgenden Analyse: Das RKI verwendet zur Berechnung der Impfeffektivität di...

The Social Science One Facebook Cooperation: A Systemic Failure

This blogpost is a detailed background statement to this comment published in Nature at https://www.nature.com/articles/d41586-020-00828-5 . Fast-Read The following text argues that the Social Science One initiative that is celebrated by Facebook as success is an systemic failure. Privacy concerns are instrumentalized to withhold data from independent researchers while similar data is still available to private companies. The hurdles for researchers at Social Science One are set in a way that it is nearly impossible to study the effect of social media on elections and democracy. This fits to the strategic interest of Facebook to play cooperative but to control the outcomes of research. Social Science One is structured in a way that it is easy for Facebook to instrumentalize this organization. We end with policy recommendations. An appendix shows that the dataset delivered by Facebook is more or less useless. Background Facebook has announced the release of a dataset that is shar...