Coder Social home page Coder Social logo

questionr's People

Contributors

briatte avatar gdutz avatar haozhu233 avatar joelgombin avatar juba avatar larmarange avatar nalimilan avatar rdrr1990 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

questionr's Issues

memisc compatibility??

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?

Personnalisation du nom des colonnes pour prop, cprop et lprop

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 ?

irec and accentuated characters

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.

Bug in `odds.ratio.multinom`

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.

prop, cprop, lprop sur tableaux à 3 (ou +) dimensions

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?

Flexible syntax

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.

Adding data extracts

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.

a labelled data set

I have prepared a labelled data set based on a demographic survey with 3 data.frame:

  • menages
  • femmes
  • enfants

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?

Changes in import for describe and lookfor

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 crash

icut crashes if the entered umber of breaks is less than 2.

Valid percentage for freq

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.

Evolutions of describe

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:

  • with labelled data, str is not easy to read due to all attributes
  • lookfor gives you only variable names and labels
  • even with str you don't see all labels of a factor if there are several
  • str doesn't show value labels
  • the purpose is not to replace summary but to give easily, quickly, and in a compact view all metadata required to manipulate your data

First 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:

  • length of the vector
  • variable label if exists
  • class of the vector
  • the first 5 values observed
  • the value labels if exist
  • the number of 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?

Fonctions diverses

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.

Une série de formateurs

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).

  • les fonctions fr pour un affichage à la française
  • les fonctions en pour un affichage à l'anglaise (avec des ' commes séparateurs de décimales)
  • les fonctions 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 anglais
  • pourcentpour les pourcentages en français
  • comp.pourcent et comp.percent pour les compléments à un

Il n'y a pas de "pour mille" pour le moment mais on peut discuter son rajout.

Arrondi OMS

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"

Opérateur %p% pour concaténer du texte

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

Intervalles de confiance d'une proportion

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

About freq

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.

Autres propositions d'ajout

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 :

Bien cordialement

irec et vecteurs numériques

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 ?

  1. On peut transmettre à 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)
  2. On supprime la case à cocher "transformer en facteur" et on propose à la place des boutons radios offrant le choix entre trois types de variables de sortie : numérique, textuelle ou facteur.

Create addNAstr instead of overriding base::addNA

The new addNA function (see #12) adds an interesting functionality, but I'm not sure it's a good way to implement it because :

  • it overrides a base function, which I'm not very happy with
  • this overriding generates a warning each time questionr is loaded
  • it duplicates the code of the base function

So 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 ?

Problem with aggregate function after loading questionr

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.

default value of keywords arg in `lookfor`

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.

Reordering with irec

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

prop, cprop, lprop with drop=TRUE and only one dimension

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]

irec doesn't accept a data.frame named "a" as input

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"

Tester les packages requis pour un projet

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 ?

Suggestion for cprop and rprop/lprop

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.

Calcul de l'âge

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 :

  • être appelée tout simplement age
  • avoir les années comme unité par défaut

Qu'en pensez vous ?

`memisc` import overrides and breaks other functions

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.

addNA avec une option string

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 ?

Value labels in freq

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:

  • "p" i.e. prefix, labels will be like "[1] Femmes"
  • "l" i.e. labels, labels of the factor will be like "Femmes"
  • "v" i.e. values, labels of the factor will be like "1"

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?

données labellisées en anglais

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 ?

odds.ratio pour les régressions logistiques

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

Improve overall package documentation

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 :

  • a knitr vignette in the package
  • wiki pages in github

Another question is to decide if this doc must be written in english or both in french and english.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.