J'essaie de convertir mes données en un document html en utilisant Rmarkdown, et je compte actuellement sur la conversion en vecteurs et l'indexation pour résoudre mon problème.
Bien que mon échantillon de données contienne 4 observations, mes ensembles de données réels contiennent plus de 30 enregistrements, donc l'indexation semble fastidieuse et non naturelle.
Existe-t-il une meilleure façon d'extraire chacun de ces éléments dans l'ordre? Toute suggestion sera appréciée.
-- title: "Rmarkdown report" output: html_document --- ```{r echo = FALSE} mydata <- data.frame(First = c("John", "Hui", "Jared"), Second = c("Smith", "Chang", "Jzu"), Sport = c("Football","Soccer","Ballet"), Age = c("12", "13", "12"), submission = c("Microbes may be the friends of future colonists living off the land on the moon, Mars or elsewhere in the solar system and aiming to establish self-sufficient homes. Space colonists, like people on Earth, will need what are known as rare earth elements, which are critical to modern technologies. These 17 elements, with daunting names like yttrium, lanthanum, neodymium and gadolinium, are sparsely distributed in the Earths crust. Without the rare earths, we wouldnât have certain lasers, metallic alloys and powerful magnets that are used in cellphones and electric cars. But mining them on Earth today is an arduous process. It requires crushing tons of ore and then extracting smidgens of these metals using chemicals that leave behind rivers of toxic waste water.", "Experiments conducted aboard the International Space Station show that a potentially cleaner, more efficient method could work on other worlds: let bacteria do the messy work of separating rare earth elements from rock. The idea is the biology is essentially catalyzing a reaction that would occur very slowly without the biology, said Charles S. Cockell, a professor of astrobiology at the University of Edinburgh. On Earth, such biomining techniques are already used to produce 10 to 20 percent of the worldâs copper and also at some gold mines; scientists have identified microbes that help leach rare earth elements out of rocks.", "Experiments conducted aboard the International Space Station show that a potentially cleaner, more efficient method could work on other worlds: let bacteria do the messy work of separating rare earth elements from rock. The idea is the biology is essentially catalyzing a reaction that would occur very slowly without the biology, said Charles S. Cockell, a professor of astrobiology at the University of Edinburgh. On Earth, such biomining techniques are already used to produce 10 to 20 percent of the worldâs copper and also at some gold mines; scientists have identified microbes that help leach rare earth elements out of rocks.")) first<- as.vector(mydata$First) sec <- as.vector(mydata$Second) age <- as.vector(mydata$Age) submission <- as.vector(mydata$submission) ``` ## **First:** `r first[1]`   **Second:** `r sec[1]` <br> **Age:** `r age[1]` **submission** <br> `r submission[1]` *** **First:** `r first[2]`   **Second:** `r sec[2]` <br> **Age:** `r age[2]` **submission** <br> `r submission[2]`
3 Réponses :
Si nous devons créer des objets dans l'environnement global, sous-ensemble les colonnes de données dans une list
, renommez-la et utilisez list2env
nm1 <- c('First', 'Second', 'Age', 'submission') nm2 <- c('first', 'sec', 'age', submission') list2env(setNames(unclass(mydata[nm1]), nm2), .GlobalEnv)
Voici un moyen d'itérer sur toutes les lignes
--- title: "Rmarkdown report" output: html_document --- ```{r echo = FALSE} # using data from above # mydata <- data.frame(...) # Define template (using column names from data.frame) template <- "**First:** `r First`   **Second:** `r Second` <br> **Age:** `r Age` **submission** <br> `r submission`" # Now process the template for each row of the data.frame src <- lapply(1:nrow(mydata), function(i) { knitr::knit_child(text=template, envir=mydata[i, ], quiet=TRUE) }) ``` # Print result to document `r knitr::knit_child(text=unlist(src))`
Ici, nous utilisons knit_child
pour prendre une chaîne de modèle, puis nous l'utilisons pour chaque ligne du data.frame. J'ai utilisé une astuce ici pour passer la ligne du data.frame comme environnement afin que le modèle puisse voir toutes les colonnes comme des variables afin que nous n'ayons pas besoin de créer les versions vectorielles de toutes les colonnes data.frame.
C'est génial!! Y a-t-il une chance que vous puissiez jeter un œil à ma modification. J'ai besoin de produire un document html par "sport", mais je ne veux pas avoir à créer (29) fichiers de démarques séparés pour y parvenir!
@NewBee C'est vraiment poser une question différente. Plutôt que de modifier votre message pour poser une nouvelle question, vous devriez commencer un nouveau message avec votre nouvelle question. Assurez-vous également de rechercher d'abord votre nouvelle question sur Google. Vous constaterez peut-être que les documents rmarkdown peuvent avoir des paramètres qui vous permettraient de générer assez facilement plusieurs documents pour différents sous-groupes.
Merci, je vais vérifier!
Salut! Je pense avoir répondu à votre question ici
Voici la réponse que j'ai donnée à votre question précédente:
Vous pouvez utiliser cat
pour ajouter le code HTML à un bloc de démarquage R afin de parcourir vos données.
Vous devez ajouter results = "asis"
à {r}
Voici la boucle:
{r results="asis", echo = FALSE} i = 1 NR_OF_ROWS <- nrow(data) # number of rows that the loop will go through while (i <= NR_OF_ROWS) { cat("\n **First:** ", data[i, 1], "  **Last:** ", data[i, 2], "<br> \n") cat("\n **Age:** ", data[i, 3], "  **Sport:** ", data[i, 4], "<br> \n") cat("\n **submission** ", data[i, 5], "<br> \n") # cat("\n <br> \n") extra space between entries cat("\n *** \n") line between entries i = i + 1 }