R에서 인덱싱하는 대신 데이터를 반복합니다.

Nov 14 2020

Rmarkdown을 사용하여 데이터를 html 문서로 변환하려고 시도하고 있으며 현재 문제를 해결하기 위해 벡터로의 변환 및 인덱싱에 의존하고 있습니다.

샘플 데이터에는 4 개의 관측치가 있지만 실제 데이터 세트에는 30 개 이상의 레코드가 있으므로 인덱싱이 번거롭고 부자연스러워 보입니다.

이러한 각 요소를 순서대로 꺼내는 더 좋은 방법이 있습니까? 어떤 제안이라도 좋을 것입니다.

 --
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]` &emsp; **Second:**  `r sec[1]` <br>
**Age:** `r age[1]`    


**submission** <br>

`r submission[1]`


***

**First:** `r first[2]` &emsp; **Second:**  `r sec[2]` <br>
**Age:** `r age[2]`    


**submission** <br>

`r submission[2]`

답변

1 MrFlick Nov 14 2020 at 02:28

모든 행을 반복하는 방법은 다음과 같습니다.

---
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` &emsp; **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))`

여기서는 knit_child템플릿 문자열을 가져 와서 data.frame의 각 행에 사용합니다. 여기서 트릭을 사용하여 data.frame의 행을 환경으로 전달하여 템플릿이 모든 열을 변수로 볼 수 있으므로 모든 data.frame 열의 벡터 버전을 만들 필요가 없습니다.

1 akrun Nov 14 2020 at 02:20

전역 환경에서 개체를 만들어야하는 경우 데이터 열을으로 하위 집합하고 list이름을 바꾼 다음list2env

nm1 <- c('First', 'Second', 'Age', 'submission')
nm2 <- c('first', 'sec', 'age', submission')
list2env(setNames(unclass(mydata[nm1]), nm2), .GlobalEnv)
1 ViviG Nov 14 2020 at 14:55

이것은 이전 질문에 대한 답변입니다.

cat데이터를 반복하기 위해 R 마크 다운 청크에 HTML 코드를 추가하는 데 사용할 수 있습니다 .

중대한

당신은 추가 results = "asis"해야{r}

다음은 루프입니다.

{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], "&emsp; **Last:** ", data[i, 2], "<br> \n")
  
  
  cat("\n **Age:** ", data[i, 3], "&emsp; **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
}

결과는 다음과 같습니다.