loop melalui data alih-alih mengindeks di R
Saya mencoba mengubah data saya menjadi dokumen html menggunakan Rmarkdown, dan saat ini saya mengandalkan konversi ke vektor dan pengindeksan untuk menyelesaikan masalah saya.
Meskipun data sampel saya memiliki 4 pengamatan, kumpulan data saya yang sebenarnya memiliki lebih dari 30 catatan, sehingga pengindeksan tampak rumit dan tidak wajar.
Apakah ada cara yang lebih baik untuk menarik setiap elemen ini secara berurutan? Ada saran yang bagus.
--
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]`
Jawaban
Berikut cara untuk mengulangi semua baris
---
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))`
Di sini kita gunakan knit_childuntuk mengambil string template dan kemudian menggunakannya untuk setiap baris data.frame. Saya menggunakan trik di sini untuk meneruskan baris data.frame sebagai lingkungan sehingga templat dapat melihat semua kolom sebagai variabel sehingga kita tidak perlu membuat versi vektor dari semua kolom data.frame.
Jika kita perlu membuat objek di global env, subset kolom data menjadi a list, ganti namanya dan gunakanlist2env
nm1 <- c('First', 'Second', 'Age', 'submission')
nm2 <- c('first', 'sec', 'age', submission')
list2env(setNames(unclass(mydata[nm1]), nm2), .GlobalEnv)
Ini adalah jawaban yang saya berikan untuk pertanyaan Anda sebelumnya:
Anda dapat menggunakan catuntuk menambahkan kode HTML ke potongan penurunan harga R untuk mengulang data Anda.
Penting
Anda harus menambahkan results = "asis"untuk{r}
Ini loopnya:
{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
}
Inilah hasilnya: