diff --git a/README.md b/README.md index 73fa0b9..588db32 100644 --- a/README.md +++ b/README.md @@ -34,10 +34,16 @@ runApp("") ``` Remember that you need to install the shiny/shinyBS packages while you have internet access! +## Languages +The app is currently available in English (default) and Portuguese. +To use the version in Portuguese, run the following command +before running the app (runGitHub(...) or runApp(...)) +```R +language <- "pt" +``` ## Current features * Access the Rsampling sample datafiles, or upload your own data in csv format * Choose between a range of statistics, or write your own R function * Select your randomization scheme, with or without replacement * Optional stratified randomization * Reactive graph showing the distribuion of the statistic of interest and estimated p-value -* Interactive tutorials on resampling statistics diff --git a/global.R b/global.R new file mode 100644 index 0000000..6b1de3a --- /dev/null +++ b/global.R @@ -0,0 +1,30 @@ +################################################## +### MULTILINGUAL VARIABLES AND FUNCTION ### +################################################# +# The default language is "en". To use the translated version, set the language such as +# > language <- "pt" +# before calling the app +language <- ifelse(exists("language"), language, "en") +dictionary <- read.csv('lang.csv', sep = ';', stringsAsFactors = FALSE, fileEncoding="UTF-8", header=TRUE) +# If the language is not recognized, does not attempt to run the app. Stop immediately: +if (! language %in% colnames(dictionary)[-1]) + stop(paste0("Language is not recognized: ", language, "\n")) +## Main translation function. Uses "language" and "dictionary" as globals, defined above +# in this file. +tr <- function(text) { + for (i in 1:length(text)) { + id <- which(dictionary$value %in% text[i]) + # Trying again: + if (length(id) == 0) + id <- which(dictionary$en %in% text[i]) + # If still no matches, prints a warning: + if (length(id) == 0) + cat(paste('No matches for text:', text[i], '\n')) + if (length(id) == 1) { + text[i] <- ifelse(language == "pt", dictionary$pt[id], dictionary$en[id]) + } else if (length(id) > 1) { + cat(paste('More than one match for text:', text[i], '\n')) + } + } + return(text) +} diff --git a/help.html b/help.html index 0c885ad..3aa6875 100644 --- a/help.html +++ b/help.html @@ -18,7 +18,7 @@

The idea behind this package is to help students to understand the logic behind these tests, with lots of flexibility on what is the statistic that will be calculated.

-

Rsampling and and this web interface were written by Andre Chalom, +

Rsampling and this web interface were written by Andre Chalom, Alexandre Adalardo, Ayana Martins and Paulo Prado.

Please visit our project webpage diff --git a/help_pt.html b/help_pt.html new file mode 100644 index 0000000..da3cd11 --- /dev/null +++ b/help_pt.html @@ -0,0 +1,31 @@ +

+ +

A Galinha Esférica foi criada por +Luisa Novara e pode ser utilizada sob a licença +CC3-by.

+
+
+

Rsampling é uma pacote gratuito e de código aberto desenvolvido + com o objetivo de ajudar no aprendizado de métodos estatísticos + baseados em permutação. + O pacote foi baseado no programa + Resampling Stats.

+

Podemos pensar na lógica por trás de um teste de significância da seguinte forma: +

+

A ideia por trás deste pacote é auxiliar na compreensão desta lógica, com grande flexibilidade de estatísticas +que podem ser calculadas.

+

Rsampling e sua interface gráfica foram escritos por Andre Chalom, + Alexandre Adalardo, Ayana Martins + e Paulo Prado.

+

Visite nossa página de projeto + e a página da biblioteca Rsampling no + github, + para aprender mais sobre o projeto e enviar sugestões ou reportar bugs.

+

Rsampling e Rsampling-shiny têm os poderes da Galinha Esférica.

+
+
diff --git a/lang.csv b/lang.csv new file mode 100644 index 0000000..d38469a --- /dev/null +++ b/lang.csv @@ -0,0 +1,182 @@ +value;en;pt +week;Week;Semana +This function calculates intercept of a linear correlation analysis between two columns, y ~ ax + b. Here, x is the independent variable, and y is the dependent variable.;This function calculates intercept of a linear correlation analysis between two columns, y ~ ax + b. Here, x is the independent variable, and y is the dependent variable.;Esta função calcula o intercepto de uma análise de correlação linear entre duas colunas, y~ax+b. Aqui x é a variável independente, e y é a variável dependente +The variance ratio function splits the data acording to a categorical variable. Then it calculates the ratio of among-group to within-group variances (F). Large differences between means of at least two groups lead to large values of F.;The variance ratio function splits the data acording to a categorical variable. Then it calculates the ratio of among-group to within-group variances (F). Large differences between means of at least two groups lead to large values of F.;A função de razão de variância divide os dados de acordo com uma variável categórica. Então ela calcula a razão entre as variâncias entre-grupos e dentro-de-grupos (F). Grandes diferenças entre as médias de pelo menos dois grupos levam a valores maiores de F +Area covered by aerial roots in mangrove trees sampled in two soil types;Area covered by aerial roots in mangrove trees sampled in two soil types;Área coberta pelas raízes aéreas em arvores de mangue amostradas em dois tipos de solo +data_input;Data input;Entrada de dados +About this data set (rhyzophora);About this data set (rhyzophora);Sobre este conjunto de dados (rhyzophora) +month;Month;Mês +help1;Use this tab to select the input data for your analysis. The first options are datasets included in the library, select the 'upload file' option to upload your own file.;Use esta aba para selecionar os dados de entrada para sua análise. As primeiras opções são conjuntos de dados incluídos na biblioteca, selecione a opção 'upload file' para enviar seu próprio arquivo. +This function calculates the sum of every values in a row. Then, it takes the mean of these values.;This function calculates the sum of every values in a row. Then, it takes the mean of these values.;Esta função calcula a soma de todos os valores em uma linha, e então calcula a média destes valores. +;This function calculates the sum of every values in a column. Then, it takes the mean of these values.;Esta função calcula a soma de todos os valores em uma coluna, e então calcula a média destes valores. +Question;Question;Pergunta +tutorial3;Protective ants;Formigas protetoras +Your version of the Rsampling library seems to be incompatible with this interface version. Please download the latest version of the library ;Your version of the Rsampling library seems to be incompatible with this interface version. Please download the latest version of the library ;Sua versão da biblioteca Rsampling parece ser incompatível com esta versão da interface. Por favor baixe a versão mais recente da biblioteca +Source: Prado, A. et al. 2013. Variações na morfologia de sustentação em;Source: Prado, A. et al. 2013. Variações na morfologia de sustentação em;Fonte: Prado, A. et al. 2013. Variações na morfologia de sustentação em +The ant colonies live in the hollow trunk of;The ant colonies live in the hollow trunk of;As colônias de formigas vivem no tronco oco de +ants in each leaf was recorded.;ants in each leaf was recorded.;recrutadas em cada folha foram registradas. +scol;Mean sum of columns;Média da soma das colunas +tutorials;Tutorials;Tutoriais +Do mangrove trees in more unstable soil allocate more biomass in supporting roots?;Do mangrove trees in more unstable soil allocate more biomass in supporting roots?; Árvores de manguezal em solos mais instáveis alocam mais biomassa para raízes de suporte? +Mean difference between soil types;Mean difference between soil types;Diferença média entre tipos de solo +Number of roots;Number of roots;N?mero de raizes +This function calculates the pairwise difference between two columns in your dataset (i.e., before and after a treatment is applied). It then averages these differences.;This function calculates the pairwise difference between two columns in your dataset (i.e., before and after a treatment is applied). It then averages these differences.;Esta função calcula a diferença par a par entre duas colunas em seu conjunto de dados(isto é, antes e depois de um tratamento ser aplicado). Ela então tira a média das duas diferenças +Rsampling version;Rsampling version;Versão do Rsampling +ssd;Column standard deviation; Desvio padrão da coluna +The higher the torque caused by the canopy, the more roots a tree wil have.;The higher the torque caused by the canopy, the more roots a tree wil have.;Quanto maior o torque causado pela copa, mais raizes terá a árvore +Sum of the squared residuals of a linear model:;Sum of the squared residuals of a linear model:;Soma dos resíduos quadrados de um modelo linear: +Mangrove trees and torque;Mangrove trees and torque;Manguezais e torque +This function calculates the correlation coefficient between two columns;This function calculates the correlation coefficient between two columns;Esta função calcula o coeficiente de correlação entre duas colunas +stat;Statistics;Estatísticas +Do ants respond more intensely to damage in younger leaves?;Do ants respond more intensely to damage in younger leaves?;Formigas respondem mais intensamente a dano em folhas mais jovens? +time;Time;Tempo +Differences in the slope of linear regressions applied to different levels of a factor:;Differences in the slope of linear regressions applied to different levels of a factor:;Diferenças na inclinação das regressões lineares aplicadas a diferentes níveis de um fator: +TWO;TWO;DUAS +This function calculates the mean of a single data column.;This function calculates the mean of a single data column.;Esta função calcula calcula a média de uma única coluna de dados +This function splits the data acording to a categorical variable. Then it calculates the mean for each group, and subtracts one from another. Note that this is designed to work with only ;This function splits the data acording to a categorical variable. Then it calculates the mean for each group, and subtracts one from another. Note that this is designed to work with only ;Esta função divide os dados de acordo com uma variável categórica. Então ela calcula a média para cada grupo, e subtrai um do outro. Note que isto é projetado para funcionar com somente +Fstatistic;Variance ratio (F) for more than 2 groups;Razão entre variâncias (F) para mais de 2 grupos +Slope of the regression between the number of roots and the ratio between canopy and trunk area;Slope of the regression between the number of roots and the ratio between canopy and trunk area;Inclinação da regressão entre o número de raízes e a razão entre Área do copa e do tronco +Balanced mangrove trees;Balanced mangrove trees;Mangues equilibristas +tutorial3;Formigas protetoras;Formigas protetoras +dataInput;dataInput;Entrada de dados +distPlot_help;Each time a new randomized data set is generated, the statistic of interest is recalculated and added to this histogram. The statistic calculated on the original data is shown as a dotted red line. Should the null hypothesis be rejected? Run this exercise inthe following tabs to find out!;Cada vez que um novo conjunto de dados é gerado, a estatística de interesse é recalculada e adicionado ao histograma. A estatística calculada sobre os dados originais é mostrada como uma linha pontilhada vermelha. A hipótese nula deve ser rejeitada? Execute este exercício nas próximas abas para descobrir! +This function calculates the slope of a linear correlation analysis between two columns, y ~ ax + b. Here, x is the independent variable, and y is the dependent variable.;This function calculates the slope of a linear correlation analysis between two columns, y ~ ax + b. Here, x is the independent variable, and y is the dependent variable.;Esta função calcula a inclinação de uma análise de correlação linear entr duas colunas, y ~x+b. Aqui Y é a variável independente e x é a variável dependente +intercept;Regression intercept;Intercepto da regressão +The language selected is not available or was not properly detected. Language was set back to the default.;The language selected is not available or was not properly detected. Language was set back to the default.;A linguagem selecionada não está disponivel ou não foi detectada adequadamente. A linguagem foi redefinida para o padrão (en) +Hypothesis;Hypothesis;Hipótese +srow;Mean sum of rows;Média da soma das linhas +Mangrove Trees;Mangrove Trees;Árvores de Mangue +;Statistic of interest;Estatística de Interesse +This function calculates the standard deviation of a single data column.;This function calculates the standard deviation of a single data column.;Esta função calcula o desvio padrão de uma única coluna de dados +slope;Regression coefficient;Coeficiente da regressão +slopePlot;slope;inclinação +corr;Correlation between columns;Correlação entre colunas +meandifc;Mean difference between columns;Diferença média entre colunas +day;Day;Dia +About this data set (azteca);About this data set (azteca);Sobre este conjunto de dados (azteca) +Here the left column of the original data has been randomized. The mean differece between soil types has been calculated for this randomized data set and is shown in the plot above. Hit the button to genetate a new randomized data set;Here the left column of the original data has been randomized. The mean differece between soil types has been calculated for this randomized data set and is shown in the plot above. Hit the button to genertate a new randomized data set;Aqui a coluna esquerda dos dados originais foi aleatorizada. A diferença média entre os tipos de solo foi calculada para este conjunto de dados aleatorizados e é mostrada no plot acima. Clique no botão para gerar um novo conjunto de dados +Correlation coefficient between columns 1 and 2:;Correlation coefficient between columns 1 and 2:;Coeficiente de correlação entre as colunas 1 e 2: +Statistics;Statistics;Estatística +Rsampling - resampling statistics in R;Rsampling - resampling statistics in R;Rsampling - Estatística baseada em permutação no R +smean;Column mean;Média da coluna +treatment;Treatment;Tratamento +resampling-title;Rsampling - resampling statistics in R;Rsampling - estatística baseada em permutação em R +Resampling;Resampling;Reamostragem +Rhizophora mangle;Rhizophora mangle;Rhizophora mangle + and can detect and expel leaf-chewing insects. To test if this response is more intense in young leaves, drops of extract of smashed young and old leaves were poured in two neighbor leaves of the same plant. After 7 minutes the number of recruited; and can detect and expel leaf-chewing insects. To test if this response is more intense in young leaves, drops of extract of smashed young and old leaves were poured in two neighbor leaves of the same plant. After 7 minutes the number of recruited; e podem detectar e expelir insetos comedores de folhas. Para testar se esta resposta é mais intensa em folhas jovens, gotas de extrato de folhas jovens e velhas esmagadas foram colocadas em duas folhas vizinhas da mesma planta. Após 7 minutos, o número de formigas +Azteca;Azteca;Azteca +Canopy area / trunk area;Canopy area / trunk area;Área da copa / Área do tronco +Does the torque caused by canopy weight result in mangrove trees with more roots?;Does the torque caused by canopy weight result in mangrove trees with more roots?;O torque causado pelo peso da copa resulta em Árvores de mangue com raízes +What is torque again? Review this concept in;What is torque again? Review this concept in;O que é o torque de novo? Reveja este conceito em +Source: Kondrat, H. 2012. Estímulos químicos de folhas novas promovem recrutamento eficiente de formigas associadas à embaúba Cecropia glaziovi (Urticaceae). Curso de campo Ecologia da Mata Atlântica (G. Machado;Source: Kondrat, H. 2012. Estímulos químicos de folhas novas promovem recrutamento eficiente de formigas associadas à embaúba Cecropia glaziovi (Urticaceae). Curso de campo Ecologia da Mata Atlântica (G. Machado;Fonte: Kondrat, H. 2012. Estímulos químicos de folhas novas promovem recrutamento eficiente de formigas associadas à embaúba Cecropia glaziovi (Urticaceae). Curso de campo Ecologia da Mata Atlântica (G. Machado +Here the left column of the original data has been randomized. The slope of the linear regression has been calculated for this randomized data set and is shown in the plot above. Hit the button to genetate a new randomized data set;Here the left column of the original data has been randomized. The slope of the linear regression has been calculated for this randomized data set and is shown in the plot above. Hit the button to genetate a new randomized data set;Aqui a coluna esquerda dos dados originais foi aleatorizada. A diferença média entre os tipos de solo foi calculada para este conjunto de dados aleatorizados e é mostrada no plot acima. Clique no botão para gerar um novo conjunto de dados +Here the second and third column of the original data have been randomized within each row. The mean differece between treatments is calculated and shown in the plot above. Hit the button to genetate a new randaomized data set;Here the second and third column of the original data have been randomized within each row. The mean differece between treatments is calculated and shown in the plot above. Hit the button to genetate a new randaomized data set;Aqui a segunda e terceira coluna dos dados originais foram aleatorizada dentro de cada linha. A diferença média entre os tratamentos é calculada e mostrada no plot acima. Clique no botão para gerar um novo conjunto de dados randomizados +custom;Custom code;Código personalizado +You already have the right version of Rsampling installed :);You already have the right version of Rsampling installed :);Você já tem a versão correta do Rsampling instalada :) +Protective ants;Protective ants;Formigas protetoras +Ratio between canopy and trunk area, both in square meters, and number of aerial roots;Ratio between canopy and trunk area, both in square meters, and number of aerial roots;Proporção entre Área da copa e do tronco, ambas em metros quadrados, e número de raízes aéreas +Next, we need to determine what is the function (i.e., the statistic) that will be applied to the data. Use one of the preset statistics or write your own.;Next, we need to determine what is the function (i.e., the statistic) that will be applied to the data. Use one of the preset statistics or write your own.;Depois, nós precisamos determinar qual é a função (isto é, a estatística) que será aplicada aos dados. Use uma das estatísticas preselecionadas ou escreva a sua própria +meandif;Mean difference between 2 groups;Diferença média entre 2 grupos +MangroveTitle;Mangrove trees and soil stability;Árvores de Mangue e estabilidade do solo +Trees located in less stable soils will have more biomass on roots;Trees located in less stable soils will have more biomass on roots; Árvores localizadas em solos menos estáveis terão mais biomassa nas raízes +tutorial1;Mangrove trees;Mangue +(Rizophoraceae) em diferentes condições de inundação do solo. Curso de campo Ecologia da Mata Atlântica (G. Machado, P.I. Prado & A.M.Z. Martini eds.). Universidade de São Paulo, São Paulo.;(Rizophoraceae) em diferentes condições de inundação do solo. Curso de campo Ecologia da Mata Atlântica (G. Machado, P.I. Prado & A.M.Z. Martini eds.). Universidade de São Paulo, São Paulo.;(Rizophoraceae) em diferentes condições de inundação do solo. Curso de campo Ecologia da Mata Atlântica (G. Machado, P.I. Prado & A.M.Z. Martini eds.). Universidade de São Paulo, São Paulo. +Download pdf!;Download pdf!;Baixar pdf! +Make sure that the data is correctly interpreted in the display below!;Make sure that the data is correctly interpreted in the display below!;Assegure-se de que os dados sejam interpretados corretamente na tabela abaixo +Sum of column 1:;Sum of column 1:;Soma da coluna 1: +Mean difference between treatments;Mean difference between treatments;Diferença média entre tratamentos +The language selected is not available or was not properly detected. Language was set back to the default.;The language selected is not available or was not properly detected. Language was set back to the default.;The language selected is not available or was not properly detected. Language was set back to the default. + categories!; categories!; categorias! +Damage on old leaves will lead to less recruited ants whencompared to damage on young leaves;Damage on old leaves will lead to less recruited ants whencompared to damage on young leaves;Dano nas folhas médias leva a menos formigas recrutadas quando comparado a dano nas folhas jovens +powered by ;powered by ;implementado em +Mean of row 3:;Mean of row 3:;Média da linha 3: +Statistic:;Statistic:;Estatística: +Numerical variable column;Numerical variable column;Coluna de variável numérica +Here is where we do the randomization!;Here is where we do the randomization!;Aqui é onde nós fazemos a aleatorização! +Below you see the result of this function applied to the original data:;Below you see the result of this function applied to the original data:;Abaixo, veja o resultado desta função aplicada aos dados originais: +Randomization type:;Randomization type:;Tipo de aleatorização +In normal resampling the data is randomized over all cells of the selected columns. If you do not check the 'With replacement' box below the data is permuted over the cells. Otherwise the data from any cell are sampled with replacement and attributed to any other cell.;In normal resampling the data is randomized over all cells of the selected columns. If you do not check the 'With replacement' box below the data is permuted over the cells. Otherwise the data from any cell are sampled with replacement and attributed to any other cell.; Na permutação normal os dados são amostrados com reposição e atribuídos a qualquer outra célula. Se você não marcar a caixa 'com reposição' abaixo os dados são permutados por todas as células. De outro modo os dados de qualquer célula são amostrados com substituição e e atribuídos a qualquer outra célula +within_row_help;The randomization is done within each row of the data. If you do not check the 'With replacement' box below the values of each row are permuted independently. Otherwise the values are sampled independently from each row and attributed only to cells of the row they were sampled from;A randomização é feita dentro de cada linha dos dados. se você não marcar a caixa 'com substituição' abaixo os valores de cada linha são permutados independentemente a partir de cada linha e atribuídos somente às células da linha da qual foram amostrados. +The randomization is done within each column of the data. If you do not check the 'With replacement' box below the values of each column are permuted independently. Otherwise the values are sampled independently from each column and attributed only to cells of the column they were sampled from.;The randomization is done within each column of the data. If you do not check the 'With replacement' box below the values of each column are permuted independently. Otherwise the values are sampled independently from each column and attributed only to cells of the column they were sampled from.; A randomização é feita dentro de cada coluna dos dados. Se você não checar a caixa 'Com reposição' abaixo, os valores de cada coluna são permutados independentemente. De outro modo, os valores são amostrados independentemente de cada coluna e atribuídos somente à celulas da coluna da qual eles foram amostrados. +Randomizes the placement of rows in the data table. If you do not check the 'With replacement' box below the position of rows are permuted. Otherwise whole rows are sampled with replacement to assemble the randomized data table. In both cases the position of values within each row is kept.;Randomizes the placement of rows in the data table. If you do not check the 'With replacement' box below the position of rows are permuted. Otherwise whole rows are sampled with replacement to assemble the randomized data table. In both cases the position of values within each row is kept.;Randomiza a colocação de linhas na tabela de dados. Se você não Checar a caixa 'Com reposição' abaixo a posição das linhas será permutada. De outro modo, linhas inteiras são amostradas com reposição para formar a tabela de dados aleatorizada. Em ambos os casos, a posição dos valores dentro de cada linha é mantida. +cols_units_help;Randomizes the placement of columns in the data table. If you do not check the 'With replacement' box below the position of columns are permuted. Otherwise whole columns are sampled with replacement to assemble the randomized data table. In both cases the position of values within each column is kept;Aleatoriza a colocação das colunas na tabela de dados.Se você não Checar a caixa 'Com reposição' abaixo a posição das linhas será permutada. De outro modo, colunas inteiras são amostradas com reposição para formar a tabela de dados aleatorizada. Em ambos os casos a posição dos valores dentro de cadacoluna é mantida +With replacement?;With replacement?;Com reposição? +Check this option if you want all the draws to be made independently (that is, with replacement) from the original data;Check this option if you want all the draws to be made independently (that is, with replacement) from the original data; Marque esta opção se quiser que todos os sorteios sejam feitos independentemente (isto é, com reposição) a partir dos dados originais +Use this to select if you want the p-value to be assigned from a two-sided hypothesis (that is, both positive and negative values can be considered extreme), or a one sided test.;Use this to select if you want the p-value to be assigned from a two-sided hypothesis (that is, both positive and negative values can be considered extreme), or a one sided test.;Use isto para selecionar se quer que o valor de p seja atribuído a partir de uma hipótese bicaudal (isto é, tanto valores positivos quanto negativos podem ser considerados extremos), ou um teste unicaudal.; +Number of trials:;Number of trials:;Número de repetições +Stratified resampling?;Stratified resampling?;Reamostragem estratificada +Check this if you want the randomization to be restricted inside groups of rows defined by a categorical value.;Check this if you want the randomization to be restricted inside groups of rows defined by a categorical value.;Marque aqui se quiser que a randomização seja restrita a dentro de grupos de linhas definidas por um valor categórico +Stratum variable:;Stratum variable:;Variável de estrato +Which columns of the data set should be randomized? This input will be parsed as R code, so 1:3 or c(1,4,5) are valid values;Which columns of the data set should be randomized? This input will be parsed as R code, so 1:3 or c(1,4,5) are valid values;Quais colunas serão reamostradas: Esta entradaserá interpretada como código do R, então 1:3 ou 1(1,4,5) são valores válidos +How many iteractions of sampling should we do?;How many iteractions of sampling should we do?;Quantas iterações de amostragem devemos fazer? +Show extremes?;Show extremes?;Mostrar extremos? +Show rejection region?;Show rejection region?;Mostrar regiões de rejeição? +Update Graph;Update Graph;Atualizar Gráfico +Download data;Download data;Baixar dados +mainplot_help1;The graph above shows the distribution of your selected statistic after repeated randomization from your data. The histograms bins in orange (if any) represent those simulations in which the statistic had a value that's;O gráfico acima mostra a distribuição de sua estatística selecionada após randomização repetida a partir dos seus dados. As colunas em laranja do histograma (se houver alguma) representam aquelas simulações nas quais a estatística tinha um valor que era +equal to or more extreme;equal to or more extreme;igual a ou mais extremo que + than the statistic calculated on your original data (represented by the dotted red line). The gray area delimits the values of the statistics under which the null hypothesis should be accepted with 5% of chance of error. The proportion of simulations with statistics more extreme than the observed (p-value of) is:; than the statistic calculated on your original data (represented by the dotted red line). The gray area delimits the values of the statistics under which the null hypothesis should be accepted with 5% of chance of error. The proportion of simulations with statistics more extreme than the observed (p-value of) is:; a estatística calculada para seus dados originais (representada pela linha pontilhada vermelha). A área cinza delimita os valores da estatísticasob os quais a hipótese nula deve ser aceita com 5% de chance de erro. A proporção de simulações com estatísticas mais extremas que o observado (valor de p) é +Original;Original;Original +Randomized;Randomized;Aleatorizado +Clear histogram;Clear histogram;Limpar histograma +Normal;Normal;Normal +Rows as units;Rows as units;Linhas como unidades +Columns as units;Columns as units;Colunas como unidades +Within rows;Within rows;Dentro de linhas +Within columns;Within columns;Dentro de colunas +Sampling...;Sampling...;Amostrando +Sampling ended with error!;Sampling ended with error!;Amstragem terminou com erro +WARNING, the statistic function should return a single number.;WARNING, the statistic function should return a single number.;AVISO, a função de estatística deve retornar um número único +incompatible;incompatible;incompatível +Run the resampling to see the graphs;Run the resampling to see the graphs;Rode a reamostragem para ver os gráficos +Distribution calculation stopped with error!;Distribution calculation stopped with error!;Calculo da distribuição terminou com erro! +no available p-value yet...;no available p-value yet...;nenhum valor de p disponível ainda +Alternative:;Alternative:;Alternativa: +;Variable column:;Coluna com a variável: +;Dependent variable column:;Coluna com a variável dependente: +;Categorical variable column:;Coluna com a variável categórica: +;Before treatment:;Antes do tratamento: +;Independent variable column:; Coluna com a variável independente: +;Numerical variable column:;Coluna com a variável numérica: +;After treatment:;Após tratamento: +Randomized data;Randomized data;Dados aleatorizados +Original data;Original data;Dados originais +Soil instability;Soil instability;Instabilidade do solo +area covered by aerial root (m2);area covered by aerial root (m2);Área coberta pela raiz aérea (m2) +canopy area / trunk area;canopy area / trunk area;área da copa / área do tronco +number of roots;number of roots;número de raízes +Treatment;Treatment;Tratamento +Number of recruited ants;Number of recruited ants;Número de formigas recrutadas +Extract of new leaves;Extract of new leaves;Extrato de folhas novas +Extract of old leaves;Extract of old leaves;Extrato de folhas velhas +slope =; slope =;inclinação +Go!;Go!;Vai! +Cecropia;Cecropia;Cecropia +What is your input data?;What is your input data?;Quais os seus dados de entrada? +Two sided;Two sided;Bicaudal +Greater;Greater;Maior que +Lesser;Lesser;Menor que +distplot_title;Distribution of the statistic of interest;Distribuição da estatística de interesse +twosided;(two-sided) p-value:;valor p (bilateral): +onesided;(one-sided) p-value:;valor p (unilateral): +;here;aqui +meandiff=;mean difference = ;diferença média = +;then reload this interface; e então recarregue esta interface +;Data set:;Conjunto de dados: +;Do it again!;De novo! +custom_help;You are free to write down your own R function to calculate any statistic over your data! The data is stored as a dataframe with the boring name of 'dataframe'. Your last line in the code should return a single number, representing the statistic of interest. Some examples of what to use include:;Você pode escrever a função em R que você quiser para calcular qualquer estatística sobre seus dados! Os dados vão ser passados para esta função com o (desinteressante) nome de 'dataframe'. A última linha no seu código precisa retornar um único número, representando a estatística de interesse. Alguns exemplos do que você pode fazer: +;Source:;Fonte: +;Header?;Cabeçalho? +;Separator;Separador de campos +;Comma;Vírgula +;Semicolon;Ponto e vírgula +;Tab;Tabulação +;Space;Espaço +;Decimal;Ponto decimal +;Dot;Ponto +;Quote;Aspas +;None;Nenhuma +;Double Quote;Aspas duplas +;Single Quote;Aspas simples +;Choose CSV file:;Escolha o nome do arquivo CSV: +;Frequency;Frequência diff --git a/server.R b/server.R index a631292..f7a6161 100644 --- a/server.R +++ b/server.R @@ -142,7 +142,7 @@ shinyServer(function(input, output, session) { # sets up a new shiny progress bar and callback function progress <- shiny::Progress$new(max=100) on.exit(progress$close()) - progress$set(message = "Sampling...", value = 0) + progress$set(message = tr("Sampling..."), value = 0) pupdate <- function(x) progress$set(value = x * progress$getMax(), detail=paste0(round(progress$getValue()), "%")) @@ -185,7 +185,7 @@ shinyServer(function(input, output, session) { output$download <- downloadHandler( filename=function() "Rsampling.csv", content=function(file) { - if(!vals$run) stop ("Sampling ended with error!") + if(!vals$run) stop (tr("Sampling ended with error!")) write.csv(vals$distribution, file) } ) @@ -195,7 +195,7 @@ shinyServer(function(input, output, session) { input$gocustomstat input$stat if(!is.null(s) && length(s) > 1) - return("WARNING, the statistic function should return a single number.") + return(tr("WARNING, the statistic function should return a single number.")) return("") }) output$needinstall <- reactive({ @@ -212,31 +212,32 @@ shinyServer(function(input, output, session) { output$distPlot <- renderPlot({ # Traps errors if (input$go == 0 | !is.numeric(vals$x)) { - plot(0,0, type='n',xlab="", ylab="", main="Run the resampling to see the graphs"); + plot(0,0, type='n',xlab="", ylab="", main=tr("Run the resampling to see the graphs")); return(); } if (! vals$run) - stop("Distribution calculation stopped with error!") + stop(tr("Distribution calculation stopped with error!")) Rsampling::dplot(dist = vals$x, svalue = isolate(svalue()), pside= input$pside, - extreme = input$extreme, vline = TRUE, rejection = input$rejection, ylim=c(0,vals$maxcount)) + extreme = input$extreme, vline = TRUE, rejection = input$rejection, ylim=c(0,vals$maxcount), + main=tr("distplot_title"), xlab=tr("Statistic of interest"), ylab=tr("Frequency")) }) ### simply displays the statistic of interest output$stat <- renderText({ # to avoid weird things when length > 1 s <- paste(round(svalue(), 3), collapse = " ") - paste("Statistic of interest: ", s, "\n", sep="") + paste(tr("Statistic of interest"),": ", s, "\n", sep="") }) ### simply displays the "p-value" output$p <- renderText({ - if (! vals$run) return ("no available p-value yet...") - side <- switch(input$pside, "Two sided" = "(two sided)", "(one sided)") + if (! vals$run) return (tr("no available p-value yet...")) + side <- switch(input$pside, "Two sided" = "twosided", "onesided") p <- switch(input$pside, "Two sided" = abs(vals$distribution) >= abs(svalue()), "Greater" = vals$distribution >= svalue(), "Lesser" = vals$distribution <= svalue() ) p <- round(sum(p) / length(vals$distribution),3) - paste(side, "p-value:", p) + paste(tr(side), p) }) ### Updates the values in the dropdowns for column selection observe({ @@ -247,14 +248,14 @@ shinyServer(function(input, output, session) { names(cols) <- colnames(d) # Please see ?switch for the syntax below label1 <- switch(input$stat, - 'smean'=,'ssd'= "Variable column: ", - 'intercept'=,'slope'=,'corr'="Dependent variable column: ", - 'meandif'=, 'Fstatistic'="Categorical variable column: ", - 'meandifc'= "Before treatment") + 'smean'=,'ssd'= tr("Variable column:"), + 'intercept'=,'slope'=,'corr'=tr("Dependent variable column:"), + 'meandif'=, 'Fstatistic'=tr("Categorical variable column:"), + 'meandifc'= tr("Before treatment:")) label2 <- switch(input$stat, - 'intercept'=,'slope'=,'corr'="Independent variable column: ", - 'meandif'=, 'Fstatistic'="Numerical variable column: ", - 'meandifc'= "After treatment: ") + 'intercept'=,'slope'=,'corr'=tr("Independent variable column:"), + 'meandif'=, 'Fstatistic'=tr("Numerical variable column:"), + 'meandifc'= tr("After treatment:")) updateSelectInput(session, "m1", choices = cols, label = label1) updateSelectInput(session, "m2", choices = cols, selected=2, label = label2) updateSelectInput(session, "stratumc", choices = cols) @@ -267,7 +268,7 @@ shinyServer(function(input, output, session) { ########################################### ########################################################################### values <- reactiveValues() - #Object where the statistics from the rondomized + #Object where the statistics from the randomized ## data sets are stored values$saveDist <- list() #Clear histrogram when button is pressed @@ -300,8 +301,8 @@ shinyServer(function(input, output, session) { colors <- matrix(rep("black",dim(dataframe)[1]*dim(dataframe)[2]),nrow=nrows,byrow=TRUE) } title <- ifelse(is.randomizedSet, - "Randomized data", - "Original data") + tr("Randomized data"), + tr("Original data")) xmin <- par("usr")[1] xmax <- par("usr")[2] ymin <- par("usr")[3] @@ -319,21 +320,22 @@ shinyServer(function(input, output, session) { par(mar = c(4,3,2,0)) Rsampling::dplot(dist = as.numeric(values$saveDist), svalue = values$origStat, extreme = FALSE, vline = TRUE, rejection = FALSE, - breaks = seq(xmin,xmax,binsize), xlim=c(xmin,xmax), ylim=c(0,30)) + breaks = seq(xmin,xmax,binsize), xlim=c(xmin,xmax), ylim=c(0,30), + main=tr("distplot_title"), xlab=tr("Statistic of interest"), ylab=tr("Frequency")) } ################################################################# ###Mangrove trees mangBoxPlot <- function(dataframe,stat,is.randomizedSet){ par(mar = c(4,4,2,2)) title <- ifelse(is.randomizedSet, - "Randomized data", - "Original data") + tr("Randomized data"), + tr("Original data")) color <- ifelse(is.randomizedSet,favoriteColor,"grey") textcolor <- ifelse(is.randomizedSet,"black","red") boxplot(root ~ soil.instability, data=dataframe, type="n", main=title, col=color, - xlab="Soil instability", ylab="area covered by aerial root (m2)") - text(2,33,paste("mean difference = \n",round(stat,4)),col=textcolor) + xlab=tr("Soil instability"), ylab=tr("area covered by aerial root (m2)")) + text(2,33,paste(tr("meandiff="),round(stat,4)),col=textcolor) } #Randomization output randomizedMang <- reactive({ @@ -377,15 +379,15 @@ shinyServer(function(input, output, session) { rhyzScatterPlot <- function(dataframe,stat,is.randomizedSet){ par(mar = c(4,4,2,2)) title <- ifelse(is.randomizedSet, - "Randomized data", - "Original data") + tr("Randomized data"), + tr("Original data")) color <- ifelse(is.randomizedSet,favoriteColor,"grey") textcolor <- ifelse(is.randomizedSet,"black","red") plot(n.roots ~ canopy.trunk, data=dataframe, pch=19, main=title, col=color, - xlab="canopy area / trunk area", ylab="number of roots") + xlab=tr("canopy area / trunk area"), ylab=tr("number of roots")) abline(lm(n.roots ~ canopy.trunk, data=dataframe)) - text(3000,150,paste("slope =",round(stat,4)),col=textcolor) + text(3000,150,paste(tr("slope ="),round(stat,4)),col=textcolor) } #Randomization output randomizedRhyz <- reactive({ @@ -425,16 +427,16 @@ shinyServer(function(input, output, session) { aztPairedPlot <- function(dataframe,stat,is.randomizedSet){ par(mar = c(4,4,2,2)) title <- ifelse(is.randomizedSet, - "Randomized data", - "Original data") + tr("Randomized data"), + tr("Original data")) color <- ifelse(is.randomizedSet,favoriteColor,"grey") textcolor <- ifelse(is.randomizedSet,"black","red") splot(dataframe$extract.new,dataframe$extract.old, col.dif = c(color, color), - main="Original data", pch=19, - xlab="Treatment", ylab="Number of recruited ants", xaxt='n') - mtext("Extract of \n new leaves",1, at=1, line=1.5) - mtext("Extract of \n old leaves",1, at=2, line=1.5) - text(1.5,46,paste("mean difference = \n", + main=tr("Original data"), pch=19, + xlab=tr("Treatment"), ylab=tr("Number of recruited ants"), xaxt='n') + mtext(tr("Extract of new leaves"),1, at=1, line=1.5) + mtext(tr("Extract of old leaves"),1, at=2, line=1.5) + text(1.5,46,paste(tr("mean difference = \n"), round(stat,4)),col=textcolor) } #Randomization output diff --git a/ui.R b/ui.R index df4a21d..57f892c 100644 --- a/ui.R +++ b/ui.R @@ -1,381 +1,304 @@ # loads the required libraries. # when adding libraries here, REMEMBER to include them as requirements on README.md library(shiny) +# Translate input widgets +##Statistic +optionsStat <- c("smean","ssd","meandif","Fstatistic","meandifc","srow", + "scol","intercept","slope","corr","custom") +names(optionsStat) <- tr(optionsStat) +##Randomization +optionsRand <- c("Normal", "Within rows", "Within columns", "Rows as units", "Columns as units") +names(optionsRand) <- tr(optionsRand) +# Original/Randomized switch +OriRand <- c("Original", "Randomized") +names(OriRand) <- tr(OriRand) +sep=c(',',';','\t',' ') +names(sep) <- tr(c("Comma", "Semicolon", "Tab", "Space")) +dec = c('.', ',') +quote = c(None='', + 'Double Quote'='"', + 'Single Quote'="'") +names(dec) <- tr(c("Dot", "Comma")) +names(quote) <- tr(c("None", "Double Quote", "Single Quote")) +Alt <- c("Two sided", "Greater", "Lesser") +names(Alt) <- tr(Alt) +### shinyUI(fluidPage(theme= "bootstrap.css", - tabsetPanel(type="tabs", id="tabEvent", - tabPanel("Rsampling", - h2("Rsampling - resampling statistics in R"), - h4("powered by ", a("Shiny", href="http://www.rstudio.com/shiny")), - includeHTML("help.html"), - h3("Rsampling version"), - conditionalPanel("output.needinstall=='ok'", - p("You already have the right version of Rsampling installed :)") - ), - conditionalPanel("output.needinstall=='incompatible'", - p("Your version of the Rsampling library seems to be incompatible with this interface - version. Please download the latest version of the library ", - a("here", href="https://github.com/lageIBUSP/Rsampling"), " then reload this interface", - style="color:#f30") - ) - ), - navbarMenu("Tutorials", - tabPanel("Mangrove trees", - column(4, - h4("Mangrove trees and soil stability"), - h6("Question"), - p("Do mangrove trees in more unstable soil allocate - more biomass in supporting roots?"), - h6("Hypothesis"), - p("Trees located in less stable soils - will have more biomass on roots"), - h6("Statisc of interest"), - p("Mean difference between soil types"), - plotOutput("distPlotMang", height=300), - h6("Each time a new randomized data set is generated, the statistic of interest is - recalculated and added to this histogram. The statistic calculated on the original data - is shown as a dotted red line. Should the null hypothesis be rejected? Run this exercise in - the following tabs to find out!"), - actionButton("clear1","Clear histogram") - ), - column(8, - fluidRow( - h5("About this data set (rhyzophora)"), - p("Area covered by aerial roots in mangrove trees sampled in two soil types"), - radioButtons('dataset', label='Data set:', choices = c("Original","Randomized"), - selected = 'Original', inline = TRUE) - ), - fluidRow( - conditionalPanel("input.dataset == 'Original'" , column(4, plotOutput("mangTable"))), - conditionalPanel("input.dataset == 'Randomized'" , column(4, plotOutput("mangTableRandom"))), - conditionalPanel("input.dataset == 'Original'" , column(8, plotOutput("mangPlot",height=300))), - conditionalPanel("input.dataset == 'Randomized'" , column(8, plotOutput("mangPlotRandom",height=300), - h5("Here the left column of the original data - has been randomized. The mean differece between - soil types has been calculated for this randomized - data set and is shown in the plot above. Hit the button - to genetate a new randaomized data set"), - actionButton("mangRand","Do it again!"))) - ), - fluidRow( - helpText("Source: Prado, A. et al. 2013. Variações na morfologia de sustentação em", em("Rhizophora mangle"), - "(Rizophoraceae) em diferentes condições de inundação do solo. Curso de campo - Ecologia da Mata Atlântica (G. Machado, P.I. Prado & A.M.Z. Martini eds.). - Universidade de São Paulo, São Paulo.", - tags$a(href="http://ecologia.ib.usp.br/curso/2013/pdf/PO4-2.pdf", "Download pdf!")) - ) - - ) - ), - tabPanel("Balanced mangrove trees", - column(4, - h4("Mangrove trees and torque"), - h6("Question"), - p("Does the torque caused by canopy weight result in mangrove - trees with more roots?"), - helpText(tags$small("What is torque again? Review this concept in", - tags$a(href="https://en.wikipedia.org/wiki/Torque", "Wikipedia"))), - h6("Hypothesis"), - p("The higher the torque caused by the canopy, the more roots - a tree wil have."), - h6("Statisc of interest"), - p("Slope of the regression between the number of roots and the ratio between canopy and trunk area"), - plotOutput("distPlotRhyz", height=300), - h6("Each time a new randomized data set is generated, the statistic of interest is - recalculated and added to this histogram. The statistic calculated on the original data - is shown as a dotted red line. Should the null hypothesis be rejected? Run this exercise in - the following tabs to find out!"), - actionButton("clear2","Clear histogram") - ), - column(8, - fluidRow( - h5("About this data set (rhyzophora)"), - p("Ratio between canopy and trunk area, both in square meters, and number of aerial roots"), - radioButtons('dataset2', label='Data set:', choices = c("Original","Randomized"), - selected = 'Original', inline = TRUE) - ), - fluidRow( - conditionalPanel("input.dataset2 == 'Original'" , column(4, plotOutput("rhyzTable"))), - conditionalPanel("input.dataset2 == 'Randomized'" , column(4, plotOutput("rhyzTableRandom"))), - conditionalPanel("input.dataset2 == 'Original'" , column(8, plotOutput("rhyzPlot",height=300))), - conditionalPanel("input.dataset2 == 'Randomized'" , column(8, plotOutput("rhyzPlotRandom",height=300), - h5("Here the left column of the original data - has been randomized. The slope of the linear - regression has been calculated for this randomized - data set and is shown in the plot above. Hit the button - to genetate a new randaomized data set"), - actionButton("rhyzRand","Do it again!"))) - ), - fluidRow( - helpText("Source: Prado, A. et al. 2013. Variações na morfologia de sustentação em", em("Rhizophora mangle"), - "(Rizophoraceae) em diferentes condições de inundação do solo. Curso de campo - Ecologia da Mata Atlântica (G. Machado, P.I. Prado & A.M.Z. Martini eds.). - Universidade de São Paulo, São Paulo.", - tags$a(href="http://ecologia.ib.usp.br/curso/2013/pdf/PO4-2.pdf", "Download pdf!")) - ) - - ) - ), - tabPanel("Protective ants", - column(4, - h4("Protective ants"), - h6("Question"), - p("Do ants respond more intensely to damage in younger leaves?"), - h6("Hypothesis"), - p("Damage on old leaves will lead to less recruited ants when - compared to damage on young leaves"), - h6("Statisc of interest"), - p("Mean difference between treatments"), - plotOutput("distPlotAzt", height=300), - h6("Each time a new randomized data set is generated, the statistic of interest is - recalculated and added to this histogram. The statistic calculated on the original data - is shown as a dotted red line. Should the null hypothesis be rejected? Run this exercise in - the following tabs to find out!"), - actionButton("clear3","Clear histogram") - ), - column(8, - fluidRow( - h5("About this data set (azteca)"), - p("The ant colonies live in the hollow trunk of", em("Cecropia"), "and can detect and expel leaf-chewing - insects. To test if this response is more intense in young leaves, drops of extract of smashed - young and old leaves were poured in two neighbor leaves of the same plant. After 7 minutes - the number of recruited", em("Azteca"),"ants in each leaf was recorded."), - radioButtons('dataset3', label='Data set:', choices = c("Original","Randomized"), - selected = 'Original', inline = TRUE) - ), - fluidRow( - conditionalPanel("input.dataset3 == 'Original'" , column(4, plotOutput("aztTable"))), - conditionalPanel("input.dataset3 == 'Randomized'" , column(4, plotOutput("aztTableRandom"))), - conditionalPanel("input.dataset3 == 'Original'" , column(8, plotOutput("aztPlot",height=300))), - conditionalPanel("input.dataset3 == 'Randomized'" , column(8, plotOutput("aztPlotRandom",height=300), - h5("Here the second and third column of the original data - have been randomized within each row. The mean differece - between treatments is calculated and - shown in the plot above. Hit the button - to genetate a new randaomized data set"), - actionButton("aztRand","Do it again!"))) - ), - fluidRow( - helpText("Source: Kondrat, H. 2012. Estímulos químicos de folhas novas promovem recrutamento eficiente - de formigas associadas à embaúba Cecropia glaziovi (Urticaceae). Curso de campo Ecologia - da Mata Atlântica (G. Machado; P.I. Prado & A.M.Z. Martini, eds.). Universidade de - São Paulo, São Paulo", - tags$a(href="http://ecologia.ib.usp.br/curso/2012/PDF/PI-Hebert.pdf", "Download pdf!")) - ) - ) + tabsetPanel(type="tabs", id="tabEvent", + tabPanel("Rsampling", + h2(tr("Rsampling - resampling statistics in R")), + h4(tr("powered by "), a("Shiny", href="http://www.rstudio.com/shiny")), + if (language=="pt") { ## USES GLOBAL VARIABLE language + includeHTML("help_pt.html") + } else { + includeHTML("help.html") + }, + h3(tr("Rsampling version")), + conditionalPanel("output.needinstall=='ok'", + p(tr("You already have the right version of Rsampling installed :)")) + ), + conditionalPanel("output.needinstall=='incompatible'", + p(tr("Your version of the Rsampling library seems to be incompatible with this interface version. Please download the latest version of the library "), + a( tr("here"), href="https://github.com/lageIBUSP/Rsampling"), tr("then reload this interface"), + style="color:#f30") + ) + ), + navbarMenu("Tutorial", + tabPanel(tr("Mangrove Trees"), + column(4, + h4(tr("MangroveTitle")), + h6(tr("Question")), + p(tr("Do mangrove trees in more unstable soil allocate more biomass in supporting roots?")), + h6(tr("Hypothesis")), + p(tr("Trees located in less stable soils will have more biomass on roots")), + h6(tr("Statistic of interest")), + p(tr("Mean difference between soil types")), + plotOutput("distPlotMang", height=300), + h6(tr("distPlot_help")), + actionButton("clear1",tr("Clear histogram")) + ), + column(8, + fluidRow( + h5(tr("About this data set (rhyzophora)")), + p(tr("Area covered by aerial roots in mangrove trees sampled in two soil types")), + radioButtons('dataset', label=tr('Data set:'), choices = OriRand, + selected = "Original", inline = TRUE) + ), + fluidRow( + conditionalPanel("input.dataset == 'Original'", column(4, plotOutput("mangTable"))), + conditionalPanel("input.dataset == 'Randomized'", column(4, plotOutput("mangTableRandom"))), + conditionalPanel("input.dataset == 'Original'", column(8, plotOutput("mangPlot",height=300))), + conditionalPanel("input.dataset == 'Randomized'", column(8, plotOutput("mangPlotRandom",height=300), + h5(tr("Here the left column of the original data has been randomized. The mean differece between soil types has been calculated for this randomized data set and is shown in the plot above. Hit the button to genetate a new randomized data set")), + actionButton("mangRand",tr("Do it again!")))) + ), + fluidRow( + helpText(tr("Source:"), " Prado, A. et al. 2013. Variações na morfologia de sustentação em", em("Rhizophora mangle"), "(Rizophoraceae) em diferentes condições de inundação do solo. Curso de campo Ecologia da Mata Atlântica (G. Machado, P.I. Prado & A.M.Z. Martini eds.). Universidade de São Paulo, São Paulo.", tags$a(href="http://ecologia.ib.usp.br/curso/2013/pdf/PO4-2.pdf", "Download pdf!")) + ) + + ) + ), + tabPanel(tr("Balanced mangrove trees"), + column(4, + h4(tr("Mangrove trees and torque")), + h6(tr("Question")), + p(tr("Does the torque caused by canopy weight result in mangrove trees with more roots?")), + helpText(tags$small(tr("What is torque again? Review this concept in"), tags$a(href="https://en.wikipedia.org/wiki/Torque", "Wikipedia"))), + h6(tr("Hypothesis")), + p(tr("The higher the torque caused by the canopy, the more roots a tree wil have.")), + h6(tr("Statistic of interest")), + p(tr("Slope of the regression between the number of roots and the ratio between canopy and trunk area")), + plotOutput("distPlotRhyz", height=300), + h6(tr("distPlot_help")), + actionButton("clear2",tr("Clear histogram")) + ), + column(8, + fluidRow( + h5(tr("About this data set (rhyzophora)")), + p(tr("Ratio between canopy and trunk area, both in square meters, and number of aerial roots")), + radioButtons('dataset2', label='Data set:', choices = OriRand, + selected = 'Original', inline = TRUE) + ), + fluidRow( + conditionalPanel("input.dataset2 == 'Original'" , column(4, plotOutput("rhyzTable"))), + conditionalPanel("input.dataset2 == 'Randomized'" , column(4, plotOutput("rhyzTableRandom"))), + conditionalPanel("input.dataset2 == 'Original'" , column(8, plotOutput("rhyzPlot",height=300))), + conditionalPanel("input.dataset2 == 'Randomized'" , column(8, plotOutput("rhyzPlotRandom",height=300), + h5(tr("Here the left column of the original data has been randomized. The slope of the linear regression has been calculated for this randomized data set and is shown in the plot above. Hit the button to genetate a new randomized data set")), + actionButton("rhyzRand",tr("Do it again!")))) + ), + fluidRow( + helpText(tr("Source:"), " Prado, A. et al. 2013. Variações na morfologia de sustentação em", em("Rhizophora mangle"),"(Rizophoraceae) em diferentes condições de inundação do solo. Curso de campo Ecologia da Mata Atlântica (G. Machado, P.I. Prado & A.M.Z. Martini eds.). Universidade de São Paulo, São Paulo.", tags$a(href="http://ecologia.ib.usp.br/curso/2013/pdf/PO4-2.pdf", "Download pdf!")) + ) + ) + ), + tabPanel(tr("Protective ants"), + column(4, + h4(tr("Protective ants")), + h6(tr("Question")), + p(tr("Do ants respond more intensely to damage in younger leaves?")), + h6(tr("Hypothesis")), + p(tr("Damage on old leaves will lead to less recruited ants whencompared to damage on young leaves")), + h6(tr("Statistic of interest")), + p(tr("Mean difference between treatments")), + plotOutput("distPlotAzt", height=300), + h6(tr("distPlot_help")), + actionButton("clear3",tr("Clear histogram")) + ), + column(8, + fluidRow( + h5(tr("About this data set (azteca)")), + p(tr("The ant colonies live in the hollow trunk of"), em(tr("Cecropia")), tr(" and can detect and expel leaf-chewing insects. To test if this response is more intense in young leaves, drops of extract of smashed young and old leaves were poured in two neighbor leaves of the same plant. After 7 minutes the number of recruited"), em(tr("Azteca")),tr("ants in each leaf was recorded.")), + radioButtons('dataset3', label='Data set:', choices = OriRand, + selected = 'Original', inline = TRUE) + ), + fluidRow( + conditionalPanel("input.dataset3 == 'Original'" , column(4, plotOutput("aztTable"))), + conditionalPanel("input.dataset3 == 'Randomized'" , column(4, plotOutput("aztTableRandom"))), + conditionalPanel("input.dataset3 == 'Original'" , column(8, plotOutput("aztPlot",height=300))), + conditionalPanel("input.dataset3 == 'Randomized'" , column(8, plotOutput("aztPlotRandom",height=300), + h5(tr("Here the second and third column of the original data have been randomized within each row. The mean differece between treatments is calculated and shown in the plot above. Hit the button to genetate a new randaomized data set")), + actionButton("aztRand",tr("Do it again!")))) + ), + fluidRow( + helpText(tr("Source:")," Kondrat, H. 2012. Estímulos químicos de folhas novas promovem recrutamento eficiente de formigas associadas à embaúba Cecropia glaziovi (Urticaceae). Curso de campo Ecologia da Mata Atlântica (G. Machado; P.I. Prado & A.M.Z. Martini, eds.). Universidade de São Paulo, São Paulo", tags$a(href="http://ecologia.ib.usp.br/curso/2012/PDF/PI-Hebert.pdf", "Download pdf!")) + ) + ) + ) + ), + tabPanel(tr("data_input"), + helpText(tr("help1")), + selectInput("datasource", + tr("What is your input data?"), + choices = c("embauba", "azteca", "peucetia", "rhyzophora", "upload file") + ), + ## the next panel only shows for the custom datasource + fluidRow(column(6,conditionalPanel( + fileInput("file", tr("Choose CSV file:"), accept='.csv'), + fluidRow( + column(3, checkboxInput("header", tr("Header?"))), + #bsTooltip("header", "First row as header"), + column(3, + radioButtons('sep', tr('Separator'), + sep, + ',')), + column(3, + radioButtons('dec', tr('Decimal'), + dec, + '.')), + column(3, + radioButtons('quote', tr('Quote'), + quote, + '"')) + ), + helpText(tr("Make sure that the data is correctly interpreted in the display below!"), style="color:#f30;"), + condition="input.datasource == 'upload file'" + ))), + tableOutput("view") + ), + tabPanel(tr("stat"), + helpText(tr("Next, we need to determine what is the function (i.e., the statistic) that will be applied to the data. Use one of the preset statistics or write your own.")), + selectInput("stat", tr("Statistic:"), + choices=optionsStat, + "meandif"), + ### Panel for custom code: + conditionalPanel( + helpText(tr("custom_help")), + strong(tr("Sum of column 1:")), p(""), code("sum(dataframe[, 1])"), p(""), + strong(tr("Mean of row 3:")), p(""), code("mean(dataframe[3, ])"), p(""), + strong(tr("Correlation coefficient between columns 1 and 2:")), p(""), + code("cor(dataframe[,1], dataframe[,2])"), p(""), + strong(tr("Sum of the squared residuals of a linear model:")), p(""), + code("my.lm <- lm(dataframe[,5] ~ dataframe[,4])"), p(""), + code("my.r <- residuals(my.lm)"), p(""), + code("sum(my.r^2)"), p(""), + strong(tr("Differences in the slope of linear regressions applied to different levels of a factor:")),p(""), + code("m1 <- lm(n.roots ~ canopy.trunk, data=dataframe, subset=soil.instability==\"medium\")"), + p(""), + code("m2 <- lm(n.roots ~ canopy.trunk, data=dataframe, subset=soil.instability==\"high\")"), + p(""), + code("coef(m1)[[2]] - coef(m2)[[2]]"),p(""), + tags$textarea(id = "customstat", rows=5, cols=40, "return(pi)"), + actionButton("gocustomstat", tr("Go!")), + condition="input.stat == 'custom'" + ), + ### Panels with help text about the selected function + conditionalPanel("input.stat == 'intercept'", + helpText(tr("This function calculates intercept of a linear correlation analysis between two columns, y ~ ax + b. Here, x is the independent variable, and y is the dependent variable.")) + ), + conditionalPanel("input.stat == 'slope'", + helpText(tr("This function calculates the slope of a linear correlation analysis between two columns, y ~ ax + b. Here, x is the independent variable, and y is the dependent variable.")) + ), + conditionalPanel("input.stat == 'corr'", + helpText(tr("This function calculates the correlation coefficient between two columns")) + ), + conditionalPanel("input.stat == 'smean'", + helpText(tr("This function calculates the mean of a single data column.")) + ), + conditionalPanel("input.stat == 'ssd'", + helpText(tr("This function calculates the standard deviation of a single data column.")) + ), + conditionalPanel("input.stat == 'srow'", + helpText(tr("This function calculates the sum of every values in a row. Then, it takes the mean of these values.")) + ), + conditionalPanel("input.stat == 'scol'", + helpText(tr("This function calculates the sum of every values in a column. Then, it takes the mean of these values.")) + ), + conditionalPanel("input.stat == 'meandif'", + helpText(tr("This function splits the data acording to a categorical variable. Then it calculates the mean for each group, and subtracts one from another. Note that this is designed to work with only "),em(tr("TWO")),tr(" categories!")) + ), + conditionalPanel("input.stat == 'Fstatistic'", + helpText(tr("The variance ratio function splits the data acording to a categorical variable. Then it calculates the ratio of among-group to within-group variances (F). Large differences between means of at least two groups lead to large values of F.")) + ), + conditionalPanel("input.stat== 'meandifc'", + helpText(tr("This function calculates the pairwise difference between two columns in your dataset (i.e., before and after a treatment is applied). It then averages these differences.")) + ), + #### Panels for the inputs selectors + conditionalPanel("input.stat != 'custom' && input.stat != 'srow' && input.stat != 'scol'", + # all other stats have a "column 1" + selectInput("m1", "Column 1", choices=1) # label and choices will be overriden! + ), + conditionalPanel("input.stat == 'slope' || input.stat == 'intercept' || input.stat == 'corr' || input.stat == 'meandif' || input.stat == 'Fstatistic' || input.stat == 'meandifc'", + # all the above stats have a "column 2" + selectInput("m2", "Column 2", choices=2) # label and choices will be overriden! + ), + helpText(tr("Below you see the result of this function applied to the original data:")), + h3(textOutput("stat")), + # displays a warning in case the statistic is not returning a single number + h4(textOutput("svaluewarning"), style="color:#f30") + ), + tabPanel(tr("Resampling"), + sidebarLayout( + sidebarPanel( + helpText(tr("Here is where we do the randomization!")), + selectInput("type", tr("Randomization type:"), + choices=optionsRand + ), + ##Help for each randomization panel + conditionalPanel( + helpText(tr("In normal resampling the data is randomized over all cells of the selected columns. If you do not check the 'With replacement' box below the data is permuted over the cells. Otherwise the data from any cell are sampled with replacement and attributed to any other cell.")), + condition = "input.type == 'Normal'"), + conditionalPanel( + helpText(tr("within_row_help")), + condition = "input.type == 'Within rows'"), + conditionalPanel( + helpText(tr("The randomization is done within each column of the data. If you do not check the 'With replacement' box below the values of each column are permuted independently. Otherwise the values are sampled independently from each column and attributed only to cells of the column they were sampled from.")), + condition = "input.type == 'Within columns'"), + conditionalPanel( + helpText(tr("Randomizes the placement of rows in the data table. If you do not check the 'With replacement' box below the position of rows are permuted. Otherwise whole rows are sampled with replacement to assemble the randomized data table. In both cases the position of values within each row is kept.")), + condition = "input.type == 'Rows as units'"), + conditionalPanel( + helpText(tr("cols_units_help")), + condition = "input.type == 'Columns as units'"), + ##bsTooltip("type", "See the help page for details on the different randomization types."), + checkboxInput("replace", tr("With replacement?")), + selectInput("pside", tr("Alternative:"), choices=Alt), + #bsTooltip("replace", tr("Check this option if you want all the draws to be made independently (that is, with replacement) from the original data")), + #bsTooltip("pside", tr("Use this to select if you want the p-value to be assigned from a two-sided hypothesis (that is, both positive and negative values can be considered extreme), or a one sided test."), "top"), + sliderInput("ntrials", tr("Number of trials:"), min=500,max=10000,value=1000,step=500), + checkboxInput("stratum", tr("Stratified resampling?")), + #bsTooltip("stratum", tr("Check this if you want the randomization to be restricted inside groups of rows defined by a categorical value.")), + conditionalPanel("input.stratum", + selectInput("stratumc", tr("Stratum variable:"), 1) + ), + conditionalPanel("input.stat == 'custom'", + helpText(tr("Which columns of the data set should be randomized? This input will be parsed as R code, so 1:3 or c(1,4,5) are valid values")), + textInput("customcols", "Columns", "1") + ), + #bsTooltip("ntrials", tr("How many iteractions of sampling should we do?")), + fluidRow(column(6, checkboxInput("extreme", tr("Show extremes?"), TRUE)), + column(6, checkboxInput("rejection", tr("Show rejection region?"), TRUE)) + ), + fluidRow(column(6, actionButton("go", tr("Update Graph"))), + column(6, downloadButton('download', tr("Download data"))) + ) + ), + mainPanel( + plotOutput("distPlot"), + helpText(tr("mainplot_help1"), em(tr("equal to or more extreme")), tr(" than the statistic calculated on your original data (represented by the dotted red line). The gray area delimits the values of the statistics under which the null hypothesis should be accepted with 5% of chance of error. The proportion of simulations with statistics more extreme than the observed (p-value of) is:")), + h3(textOutput("p")) + ) + ) ) - ), - tabPanel("Data input", - helpText("Use this tab to select the input data for your analysis. The first options are - datasets included in the library, select the \"upload\" option to upload your own - file."), - selectInput("datasource", - "What is your input data?", - choices = c("embauba", "azteca", "peucetia", "rhyzophora", "upload file") - ), - ## the next panel only shows for the custom datasource - fluidRow(column(6,conditionalPanel( - fileInput("file", "Choose CSV file:", accept='.csv'), - fluidRow( - column(3, checkboxInput("header", "First row as header?")), - column(3, - radioButtons('sep', 'Separator', - c(Comma=',', - Semicolon=';', - Tab='\t', - Space=' '), - ',')), - column(3, - radioButtons('dec', 'Decimal', - c(dot ='.', - comma=','), - '.')), - column(3, - radioButtons('quote', 'Quote', - c(None='', - 'Double Quote'='"', - 'Single Quote'="'"), - '"')) - ), - helpText("Make sure that the data is correctly interpreted in the display below!", style="color:#f30;"), - condition="input.datasource == 'upload file'" - ))), - tableOutput("view") - ), - tabPanel("Statistics", - helpText("Next, we need to determine what is the function (i.e., the statistic) that will be applied to the data. Use one of the preset statistics or write your own."), - selectInput("stat", "Statistic:", - choices=c("Column mean" = "smean", - "Column standard deviation" = "ssd", - "Mean difference between 2 groups" = "meandif", - "Variance ratio (F) for more than 2 groups" = "Fstatistic", - "Mean difference between columns" = "meandifc", - "Mean sum of rows" = "srow", - "Mean sum of columns" = "scol", - "Regression intercept" = "intercept", - "Regression coefficient" = "slope", - "Correlation between columns" = "corr", - "Custom code" = "custom"), - "meandif"), - ### Panel for custom code: - conditionalPanel( - helpText("You are free to write down your own R function to calculate any statistic - over your data! The data is stored as a dataframe with the boring name of - \"dataframe\". Your last line in the code should return a single number, representing - the statistic of interest. Some examples of what to use include:"), - strong("Sum of column 1:"), p(""), code("sum(dataframe[, 1])"), p(""), - strong("Mean of row 3:"), p(""), code("mean(dataframe[3, ])"), p(""), - strong("Correlation coefficient between columns 1 and 2:"), p(""), - code("cor(dataframe[,1], dataframe[,2])"), p(""), - strong("Sum of the squared residuals of a linear model:"), p(""), - code("my.lm <- lm(dataframe[,5] ~ dataframe[,4])"), p(""), - code("my.r <- residuals(my.lm)"), p(""), - code("sum(my.r^2)"), p(""), - strong("Differences in the slope of linear regressions - applied to different levels of a factor:"), - code("m1 <- lm(n.roots ~ canopy.trunk, data=dataframe, subset=soil.instability==\"medium\")"), - p(""), - code("m2 <- lm(n.roots ~ canopy.trunk, data=dataframe, subset=soil.instability==\"high\")"), - p(""), - code("coef(m1)[[2]] - coef(m2)[[2]]"),p(""), - tags$textarea(id = "customstat", rows=5, cols=40, "return(pi)"), - actionButton("gocustomstat", "Go!"), - condition="input.stat == 'custom'" - ), - ### Panels with help text about the selected function - conditionalPanel("input.stat == 'intercept'", - helpText("This function calculates intercept of - a linear correlation analysis between two columns, y ~ ax + b. Here, x is the - independent variable, and y is the dependent variable.") - ), - conditionalPanel("input.stat == 'slope'", - helpText("This function calculates the slope of - a linear correlation analysis between two columns, y ~ ax + b. Here, x is the - independent variable, and y is the dependent variable.") - ), - conditionalPanel("input.stat == 'corr'", - helpText("This function calculates the correlation coefficient between two columns") - ), - conditionalPanel("input.stat == 'smean'", - helpText("This function calculates the mean of a single data column.") - ), - conditionalPanel("input.stat == 'ssd'", - helpText("This function calculates the standard deviation of a single data column.") - ), - conditionalPanel("input.stat == 'srow'", - helpText("This function calculates the sum of every values in a row. Then, it takes - the mean of these values.") - ), - conditionalPanel("input.stat == 'scol'", - helpText("This function calculates the sum of every values in a column. Then, it takes - the mean of these values.") - ), - conditionalPanel("input.stat == 'meandif'", - helpText("This function splits the data acording to a categorical variable. Then it calculates - the mean for each group, and subtracts one from another. Note that this is designed - to work with only ",em("TWO")," categories!") - ), - conditionalPanel("input.stat == 'Fstatistic'", - helpText("The variance ratio function splits the data acording to a categorical variable. - Then it calculates - the ratio of among-group to within-group variances (F). - Large differences between means of at least two groups lead to large values of F.") - ), - conditionalPanel("input.stat== 'meandifc'", - helpText("This function calculates the pairwise difference between two columns in - your dataset (i.e., before and after a treatment is applied). It then - averages these differences.") - ), - #### Panels for the inputs selectors - conditionalPanel("input.stat != 'custom' && input.stat != 'srow' && input.stat != 'scol'", - # all other stats have a "column 1" - selectInput("m1", "Column 1", choices=1) # label and choices will be overriden! - ), - conditionalPanel("input.stat == 'slope' || input.stat == 'intercept' || - input.stat == 'corr' || input.stat == 'meandif' || - input.stat == 'Fstatistic' || input.stat == 'meandifc'", - # all the above stats have a "column 2" - selectInput("m2", "Column 2", choices=2) # label and choices will be overriden! - ), - helpText("Below you see the result of this function applied to the original data:"), - h3(textOutput("stat")), - # displays a warning in case the statistic is not returning a single number - h4(textOutput("svaluewarning"), style="color:#f30") - ), - tabPanel("Resampling", - sidebarLayout( - sidebarPanel( - helpText("Here is where we do the randomization!"), - selectInput("type", "Randomization type:", - choices=c("Normal", "Within rows", "Within columns", - "Rows as units", "Columns as units") - ), - ##Help for each randomization panel - conditionalPanel( - helpText( - "In normal resampling the data is randomized over all cells of the selected columns. If you do not check the 'With replacement' box below the data is permuted over the cells. Otherwise the data from any cell are sampled with replacement and attributed to any other cell."), - condition = "input.type == 'Normal'"), - conditionalPanel( - helpText( - "The randomization is done within each row of the data. - If you do not check the 'With replacement' box below the values of - each row are permuted independently. Otherwise - the values are sampled independently from each row and - attributed only to cells of the row they were sampled from."), - condition = "input.type == 'Within rows'"), - conditionalPanel( - helpText( - "The randomization is done within each column of the data. - If you do not check the 'With replacement' box below the values of - each column are permuted independently. Otherwise - the values are sampled independently from each column and - attributed only to cells of the column they were sampled from."), - condition = "input.type == 'Within columns'"), - conditionalPanel( - helpText( - "Randomizes the placement of rows - in the data table. If you do not check the 'With replacement' box below the - position of rows are permuted. Otherwise - whole rows are sampled with replacement to assemble the randomized data table. - In both cases the position of values within each row is kept."), - condition = "input.type == 'Rows as units'"), - conditionalPanel( - helpText( - "Randomizes the placement of columns - in the data table. If you do not check the 'With replacement' box below the - position of columns are permuted. Otherwise - whole columns are sampled with replacement to assemble the randomized data table. - In both cases the position of values within each column is kept."), - condition = "input.type == 'Columns as units'"), - checkboxInput("replace", "With replacement?"), - selectInput("pside", "Alternative hypothesis:", choices=c("Two sided", "Greater", "Lesser")), - sliderInput("ntrials", "Number of trials:", min=500,max=10000,value=1000,step=500), - checkboxInput("stratum", "Stratified resampling?"), - conditionalPanel("input.stratum", - helpText("Check this if you want the randomization to be restricted inside groups of rows defined by a categorical value."), - selectInput("stratumc", "Stratum variable: ", 1) - ), - conditionalPanel("input.stat == 'custom'", - helpText("Which columns of the data set should be randomized? - R code such as 1:3 or c(1,4,5) are valid values"), - textInput("customcols", "Columns", "1") - ), - fluidRow(column(6, checkboxInput("extreme", "Show extremes?", TRUE)), - column(6, checkboxInput("rejection", "Show rejection region?", TRUE)) - ), - fluidRow(column(6, actionButton("go", "Run sampling!")), - column(6, downloadButton('download', "Download data")) - ) - ), - mainPanel( - plotOutput("distPlot"), - helpText("The graph above shows the distribution of your selected statistic after repeated - randomization from your data. The histograms bins in orange (if any) represent those - simulations in which the statistic had a value that's ", em("equal - to or more extreme"), " than the statistic calculated on your original data - (represented by the dotted red line). The gray area delimits the values of the statistics under which the null hypothesis should be accepted with 5% of chance of error. The proportion of simulations with statistics more extreme than the observed (p-value of) is:"), - h3(textOutput("p")) - ) - ) - ) - ) + ) ))