juba / questionr Goto Github PK
View Code? Open in Web Editor NEWR package to make surveys processing easier
Home Page: https://juba.github.io/questionr/
R package to make surveys processing easier
Home Page: https://juba.github.io/questionr/
Not a precise point but rather a general discussion.
Do you use the memisc
package? It's a way to store more information about variables, labels and missing codes but I'm also reluctant to use data.set instead of proper data.frame as therefore some functions could not be used directly.
For me, a good way would to be able to use a data.set in the same way I'm using a data.frame. Some functions in questionr
could not be used directly with a data.set (for example freq
) but adding compatibility would be easy.
So, it's more a general discussion, do you think that compatibility with memisc data.set
should be done when possible within questionr
or is it not important for questionr
?
Lorsque l'on utilise une des ces fonctions, on obtient un tableau avec une colonne Ensemble, ce qui est approprié uniquement pour une sortie en Français.
Ne devrait-ton pas utiliser plutôt une chaine de texte, voir carrément permettre de personnaliser le label ?
A very short screencast could be a good way to show how the "interactive" functions (irec
, iorder
, icut
) work and how to use the interface.
I just constated a problem of character encoding when using irec. I didn't have time to check the exact source of the problem. Probably a missing encoding declaration in some function.
When using irec, icut and iorder, if the data frame passed as argument is in an object called df, the function fails because of get
logic :
irec(df, qualif)
Un addin manager vient de sortir : https://github.com/csgillespie/addinmanager
Ca peut valoir le coup d'y déclarer les nouveaux addins de questionr
I just found a small bug in odds.ratio.multinom
. The function display the coefficients and not the odds ratio (exp of coefficients).
I will fix it today and will sent a pull request tonight.
Lorsque l'on croise 3 ou 4 variables, il n'est pas possible d'utiliser l'une de ces trois fonctions.
À titre d'exemple, on peut appliquer addmargins
sur un tel tableau. Cela ajoutera les colonnes et lignes totales pour chaque sous-tableau du premier facteur et ajoutera un tableau avec la somme sur ce premier facteur.
Pourrait-on envisager d'étendre ces trois fonctions de la même manière, ou, a minima, pour chacun des sous-tableaux de dimension 2?
When you know R, a variable is data$var
or data[, "var"]
. But if you are learning R, perhaps data, "var"
is a convenient notation too. This becomes handy when you are handling more than one variable, because data[, c("var1", "var2")]
is painful, whereas data, "var1", "var2"
is less painful.
This issue contains a similar suggestion.
I suggest implementing that syntax wherever possible, i.e. when it costs nothing else than modifying the call statement of a function and adding one line to pass the (variable) names to the data frame. I have no evidence to prove this might come out well, so it needs thought.
I was thinking of adding various data extracts to the package. I have coded a few download-and-prepare procedures, based on publicly available data (others, like Anthony Damico, are doing at a higher level, with complex survey objects and so on).
Adding an ANES extract should be doable, since Martin Elff did it in memisc
(see the package vignette, which uses the ANES 1948). The question is: adding a cross-sectional component or a longitudinal one. The latter might require adding panel functions to the package for consistency.
I have prepared a labelled data set based on a demographic survey with 3 data.frame:
It's appropriate for examples for freq
, ltabs
or describe
and could be used for learning how to merge tables.
Would it be appropriate to add it to questionr
?
Hi @briatte,
I just pushed questionr 0.2 on CRAN, and the package check against R-devel raised an error because the memisc
package was listed in both Imports
and Suggests
in the DESCRIPTION
file.
The workaround I found is to remove memisc
from Suggests
, and change the way the description
function is called from lookfor
and describe
(see the Fix import problems commit).
I had to call description
the following way :
#suppressMessages(suppressWarnings(require(memisc)))
l <- as.vector(memisc::description(data))
I checkes that the examples are still working, but maybe you should take a closer look to be sure that my change didn't had any side effect.
Thanks !
icut
crashes if the entered umber of breaks is less than 2.
For a frequency table, SPSS provide both global percentage (including missing) and valid percentage (excluding NA).
It could be useful that by default freq
also show valid percentage (to avoid to call the function twice, once with NA and once excluding NA).
If you are OK with the idea, I can propose a pull request.
Idea : create a shiny interface for a variable dictionary. Possible features : interactive search in variable names / variables labels (lookfor
), summary
, etc.
Following #51, I have some idea for describe
.
However, I don't know if you would prefer to change describe
or to name it differently.
There are several considerations:
str
is not easy to read due to all attributeslookfor
gives you only variable names and labelsstr
you don't see all labels of a factor if there are severalstr
doesn't show value labelssummary
but to give easily, quickly, and in a compact view all metadata required to manipulate your dataFirst of all, describe
will be transformed to a method (if you prefer to keep describe
as it is, we can try to find another verb).
describe
could be apply directly to a vector. It will return a text of class description
. We will have a print
method for description
who simply print that text in the console.
describe
should give you at least:
NA
Some examples:
> describe(d$labelled_var)
[2000] The variable label of my variable
labelled 1 1 1 2 2 ...
2 labels: [1] femmes [2] hommes
Min: 1 - Max: 2 - NAs: 0
> describe(d$date_var)
[2000]
Date 1997-03-07 1982-01-06 1979-01-01 1968-03-29 1986-05-25 ...
Min: 1962-02-07 - Max: 1997-03-13 - NAs: 12
> describe(d$factor_var)
[2000] A factor variable with variable label
Factor "Employe" NA "Technicien" "Technicien" "Employe" ...
7 levels: Ouvrier specialise | Ouvrier qualifie | Technicien | Profession intermediaire
| Cadre | Employe | Autre
NAs: 347
Of course, the method will also be defined for a data.frame will use the methods for each variable.
> describe(d)
"tbl_df" "tbl" "data.frame" [2 000 obs. x 3 var.]
$labelled_var: The variable label of my variable
labelled 1 1 1 2 2 ...
2 labels: [1] femmes [2] hommes
Min: 1 - Max: 2 - NAs: 0
$date_var:
Date 1997-03-07 1982-01-06 1979-01-01 1968-03-29 1986-05-25 ...
Min: 1962-02-07 - Max: 1997-03-13 - NAs: 12
$factor_var: A factor variable with variable label
Factor "Employe" NA "Technicien" "Technicien" "Employe" ...
7 levels: Ouvrier specialise | Ouvrier qualifie | Technicien | Profession intermediaire
| Cadre | Employe | Autre
NAs: 347
We could also keep for data frames the current behaviour of describe
allwoing to select just a sub-sample of variables, i.e. describe(d, "date_var", "factor_var")
.
What do you think?
Please add support for computing proportions of more than 2 dimensions. especially cross-tab of a multi response variable and 2 (or more) single response variables.
Thanks
Should the multiplot
function (proposed here http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/) be included in questionr
?
J'ai quelques fonctions prêtes à l'emploi dans JLutils (mon package fourre-tout) et que j'utilise au quotidien. Je me demande si certaines n'auraient pas vocation à rejoindre questionr.
Pour la réalisation de graphiques, il est important de mettre en forme les axes correctement (nombre de décimales, affichage en pourcent, séparateurs de milliers). De même lorsque lorsque l'on affiche des résultats au propre dans un rapport R markdown.
Par ailleurs, la mise en forme diffère entre l'anglais et le français (virgule pour séparer les décimales en français et espace avec le symbole %).
https://github.com/larmarange/JLutils/blob/master/R/formating.R contient toute une série de fonctions prêtes à l'emploi couvrant la plupart des usages courants. Quelques exemples :
> fr0(123456.789)
[1] "123 457"
> fr2(123456.789)
[1] "123 456,79"
> en2(123456.789)
[1] "123'456.79"
> int2(123456.789)
[1] "123 456.79"
> pourcent1(0.123456)
[1] "12,3 %"
> pourcent3(0.123456)
[1] "12,346 %"
> percent2(0.123456)
[1] "12.35%"
> comp.percent1(0.123)
[1] "87.7%"
> comp.pourcent0(0.123)
[1] "88 %"
> comp.pourcent1(0.123)
[1] "87,7 %"
Le chiffre en suffixe indique le nombre de décimales (il y a aussi toujours une version générique où le nombre de décimales est passé en argment).
fr
pour un affichage à la françaiseen
pour un affichage à l'anglaise (avec des ' commes séparateurs de décimales)int
pour un affichage dit international demandé par certaines revues (espace pour les milliers, point pour les décimales. En passant, la revue Lancet recommande pour sa part un middle point comme séparateur de décimales. Une version à rajouter ?)percent
pour les pourcentages en anglaispourcent
pour les pourcentages en françaiscomp.pourcent
et comp.percent
pour les compléments à unIl n'y a pas de "pour mille" pour le moment mais on peut discuter son rajout.
C'est peut être accessoire pour questionr
. L'OMS a une règle d'arrondi un peu particulière :
In WHO publications, population numbers are usually presented as follow:
- 0 if < 5
- 10 if ≥ 5 and < 10
- one significant digit if ≥ 10 and < 100
- two significant digits if ≥ 100 and < 10 millions
- three significant digits if ≥ 10 millions
> who.format(c(3, 8, 42, 75, 45678, 9876543, 12345678))
[1] " 0" " 10" " 40" " 80" " 46 000" " 9 900 000" "12 300 000"
La fonction paste
sert assez souvent dès qu'on fait des graphiques programmatiques ou des rapports automatisés. x %p% y
est l'équivalent de paste0(x, y)
. C'est plus lisible et plus rapide à écrire.
cf. https://github.com/larmarange/JLutils/blob/master/R/concatenate.R
https://github.com/larmarange/JLutils/blob/master/R/prop.ci.R
Des wrappers pour prop.test
pour récupérer facilement des intervalles de confiance d'une proportion.
> freq(d$sport)
n % val%
Non 1277 63.8 63.8
Oui 723 36.1 36.1
NA 0 0.0 NA
> prop.ci(d$sport)
[1] 0.6169447 0.6595179
> prop.ci.lower(d$sport)
[1] 0.6169447
> prop.ci.upper(d$sport)
[1] 0.6595179
> prop.ci(d$sport, conf.level = 0.9)
[1] 0.6204011 0.6562194
> prop.ci(table(d$sport))
[1] 0.6169447 0.6595179
> prop.ci(d$sport=="Non")
[1] 0.6169447 0.6595179
> prop.ci(d$sport=="Oui")
[1] 0.3404821 0.3830553
>
> prop.ci.lower(c(1277, 723), n = 2000)
[1] 0.6169447 0.3404821
> prop.ci.upper(c(1277, 723), n = 2000)
[1] 0.6595179 0.3830553
Très utile par exemple pour des aggrégations, pour préparer les données d'un graphique. Exemple :
> d <- as.data.table(d)
> res <- d[,.(freq=.N),by=.(sexe,sport)]
> res[, n := sum(freq), by=sexe]
> res[, prop := freq/n]
> res[, prop.l := prop.ci.lower(freq, n)]
> res[, prop.h := prop.ci.upper(freq, n)]
> res
sexe sport freq n prop prop.l prop.h
1: Femme Non 747 1101 0.6784741 0.6498433 0.7058435
2: Femme Oui 354 1101 0.3215259 0.2941565 0.3501567
3: Homme Oui 369 899 0.4104561 0.3782002 0.4434870
4: Homme Non 530 899 0.5895439 0.5565130 0.6217998
Bref, si des fonctions vous semblent relever de questionr, pas de souci pour les y transférer. Sinon, ça restera dans le "foure-tout";
Cdlt
Big bug : icut
fails if there's a NA in the variable and the "add extreme values" box is checked.
To reproduce :
data(happy)
icut(happy,age)
What is the purpose of this line?
if (is.factor(x)) x <- factor(x, exclude=exclude)
The exclusion is done 2 lines later in
tab <- table(x, exclude=exclude)
Furthermore, should we change this line in
tab <- table(x, exclude=exclude, useNA="ifany")
?
It allows to exclude a specific value but to keep the missing values.
Sorry, please just ignore...
When importing SPSS/Stata files with haven, variable labels are stored as an attribute of each column.
We should take it into account in lookfor
Toujours dans le cadre de la préparation d'un cours, j'ai exhumé d'autres petits scripts jusqu'à présent éparpillés au sein de divers projets. Je ne sais pas ce qui aurait sa place au sein de questionr
. Voici la liste des fonctions. Pour celles qui pourraient rejoindre questionr
, je peux préparer un pull request :
best.cutree
(http://joseph.larmarange.net/?Ou-couper-un-dendrogramme) permet de calculer la meilleure partition à partir d'un dendrograme selon le critère de la plus grande perte relative d'inertie. Propose aussi une représentation graphique. Reprend le critère utilisée par la fonction HCPC
de FactoMineR
mais en permettant de l'appliquer à n'importe quel dendrogramme calculé avec hclust
ou agnes
.duplicated2
(http://joseph.larmarange.net/?Rechercher-et-visualiser-les) pour visualiser les doublons dans un fichier de données. Utile pour visualiser les lignes ayant un même identifiant par exemple.s.freq
(http://joseph.larmarange.net/?Representer-des-effectifs-dans-le) permet de représenter les individus dans le plan factoriel avec un carré dont la taille est proportionnelle au nombre d'invidus projetés au même endroit. S'utilise dans le cadre d'une analyse factorielle réalisée avec ade4
.na.rm
(http://joseph.larmarange.net/?Manipulation-de-donnees-quelques) manipulation de données (data.frame). Similaire à na.omit
mais avec la possibilité de spécifier la liste des variables à prendre en compte.rm.unused.levels
(http://joseph.larmarange.net/?Manipulation-de-donnees-quelques) manipulation de données (data.frame). Permet de supprimer les niveaux inutilisés de variables facteur. Assez fréquent lorsque l'on importe certaines enquêtes type EDS depuis SPSS. Il y a des facteurs déclarés dans SPSS mais qui ne sont pas observés dans le fichier de données.seq.heatmap
(http://joseph.larmarange.net/?Representer-un-tapis-de-sequences) Dans le cadre d'une analyse de séquences avec TraMineR. Représentation graphique du tapis des séquences ordonnées selon un dendrogrammeA2Rplot
script de Romain François, disponible ici (http://addictedtor.free.fr/packages/A2R/lastVersion/R/code.R) mais non distribué au sein d'un plugin. Permet de représenter un dendrogramme avec des branches colorées (voir http://rpubs.com/gaston/dendrograms dernier exemple)Bien cordialement
Je viens de faire un test rapide et la fonction irec
n'acceptent que des variables textuelles et des facteurs. Or, lorsqu'on importe des données en conservant les codes numériques (ce qui est le cas par exemple avec des données labellisées), on peut aussi avoir besoin de procéder à ce type de recodage, puisque notre variable numérique correspond dans ce cas à des données catégorielles.
Pourrait-on envisager l'évolution suivante ?
irec
soit une variable numérique, soit une variable textuelle, soit un facteur (NB : les vecteurs labellisés sont bien inclus puisqu'ils restent par nature des vecteurs numériques et textuels, ce qui peut être testé avec is.numeric
et is.character
)The new addNA
function (see #12) adds an interesting functionality, but I'm not sure it's a good way to implement it because :
base
function, which I'm not very happy withquestionr
is loadedbase
functionSo I wonder if it would not be better, instead of overriding and adding an argument to addNA
, to create a new addNAstr
function (or whatever better name we could find) which would be something like (not tested) :
addNAstr <- function(..., value=NULL) {
x <- addNA(...)
s <- ifelse(is.character(value), value, "NA")
levels(x)[is.na(levels(x))] <- s
x
}
What do you think ?
eg "Apple" should not match "Crab Apple". I suggest replacing grep with %in% in the for loop.
See pull request #58
If we reorder var
, the recoded variable name should be var
, not var_rec
.
Add warning on already existing variable only if the new name is different from var
.
We definitely need to add tests to the package, especially for the table functions.
When running as an addin, check if selection is an object name (x
or d$var
).
After using questionr package i have problem with aggregate
tab1<-aggregate(form, data=aqm, FUN=function(x) c(mean =mean(x), s_d =sd(x)))
Error in eval(expr, envir, enclos) : can't find function "fapply"
After detach questionr the problem does not go away, needs restart R.
irec
fails if a factor level is the empty string ""
.
I'm not sure if the current default value ("weight|sample"
) is very useful except as an example of usage.
Very often, I'm calling lookfor
with keywords=""
just to see all the available variables with their imported labels.
Should it be the appropriate default value for keywords
? If we don't specify anything, we display all variables.
Just discovered the interactive functions. I simply love the concepts.
A quick message before to forgot: could be great to be able to reorder the levels directly in irec
.
Thanks again for all your work
Hello,
I had recently the case of a cross-table with observations for only one column.
prop, lprop and cprop failed because of r tab <- tab[rowSums(tab) > 0, colSums(tab) > 0]
induce a reduction in the number of dimension.
The correction is easy:
tab <- tab[rowSums(tab) > 0, colSums(tab) > 0, drop=FALSE]
Ajouter un nouveau jeu de données sur les données du recensement 2012
irec gives an error if we pass it a data.frame named a
as the first argument.
library(questionr)
# simulate data
d <- data.frame(l=letters[1:4],x=rnorm(100))
a <- subset(d,l != "d")
irec(d,l)
# works fine
irec(a,l)
# Error in irec(a, l) : ‘a must be a data frame.’
irec("a",l)
# Error in irec(a, l) : ‘a must be a data frame.’
exists("a")
# [1] TRUE
class(a)
# [1] "data.frame"
Faisant suite à larmarange/analyse-R#35, je me demande si ca ne vaudrait pas le coup d'ajouter une fonction à questionr pour détecter tous les packages appelés dans le cadre d'un projet (i.e. fichiers .R, .r, .Rmd, .rmd, .Rhtml, .rhtml, .rnw, .Rnw, .snw, .Snw, exploration du working directory et de ses sous-répertoires) et installation le cas échéant des packages manquants ?
For cprop
, it could be useful to add an option for displaying an additional line with the total number of individuals per col.
Same idea for rprop
.
Le calcul d'un âge (différence entre deux dates) n'est pas une tâche si facile si l'on souhaite le faire proprement. Par défaut, R calcule les différentes entre deux dates en nombre de jours. Une division par 365.25 n'est pas l'approche la plus pertinente.
Il existe une fonction faisant ce calcul proprement : https://github.com/jknowles/eeptools/blob/master/R/age_calc.R
Elle est fournit dans un package (epptools) qui a de nombreuses dépendances. Dès lors, il n'est pas forcément très approprié de charger epptools juste pour cette fonction.
Je me demandais si cette fonction n'aurait pas vocation à intégrer questionr, avec quelques petites modifications :
age
Qu'en pensez vous ?
The fact that we import functions from the memisc
package overrides some base functions and breaks things.
For example, loading questionr
replaces the base aggregate.formula
function with the one in memisc
, making example(aggregate)
or example(microbenchmark)
broken.
I thought that the current DESCRIPTION
and NAMESPACE
would prevent it, but it is not the case.
La fonction addNA créé un nouveau facteur dont le nom est NA lui-même. Cela pose des problèmes avec certaines fonctions comme xtable ou bien plot(allEffects(reg)) duu package effects.
Une solution consiste à surcharger addNA en ajoutant un argument pour en faire une modalité avec un nom textuel (cf. http://stackoverflow.com/a/5817181) voir en permettant carrément à as.string de prendre la valeur textuelle de son choix.
Est-ce que ce type de fonction améliorée à vocation à rejoindre questionr ?
Following #47 and #51 and the inclusion of get_var_labels
and get_val_labels
, I would like to create a function to_factor
that take a vector and will return a factor.
If x
is already a factor, it will return directly x
.
If not, it will convert x
to a factor. If some of the values found in x
have a value label, then the label will be used. If not, value will be used. The idea is that we don't need to know in advance in labels exits or not, nor to check that all values have a label.
I'm also thinking of an option with 3 possibilities:
With this function, it will be easy to modify freq
and simply to apply to_factor
to x
at the beginning.
What do you think?
Le set fecondite
permets de montrer ce que sont des données labellisées. Seul souci c'est en français. Je donne quelques cours en anglais en ce moment et je vais très probablement en faire une version anglaise (renommage des noms des data frames, des noms des variables et des étiquettes).
Est-ce que ca vaut le coup d'inclure également dans questionr
ce set fertility
?
Bonjour,
la préparation d'un cour est toujours l'occasion de déterrer les vieilles astuces et morceaux de code.
Lorsque l'on réalise une régression logistique, les odds.ratio ne sont pas directement fournis par summary. De plus, dans le cas d'une régression multinomiale, les valeurs de p doivent également être calculées.
On peut assez facilement tout faire à la main, mais il est plus difficile d'avoir un seul tableau compact avec tous les paramètres réunis.
C'est pourquoi je m'étais fait une fonction odds.ratio() qui fournit rapidement les OR, leur intervalles de confiance et la valeur de p, ce qui permets un gain de temps lors de d'analyse.
J'ai posté le code à cette adresse http://joseph.larmarange.net/?Calculer-les-Odds-Ratio-d-une mais je me dis que cela pourrait éventuellement être pertinent pour questionr, la régression logistique étant devenu fréquente dans le domaine de l'analyse d'enquêtes.
Bien cordialement
It would be great to provide some kind of documentation which would describe the different functions offered by questionr, and the way to use them.
I see two possible formats here :
Another question is to decide if this doc must be written in english or both in french and english.
The variable doesn't work if a data.table is passed instead of a data frame. Add with=FALSE
or something like that.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.