【问题标题】:loop through data instead of indexing in R循环遍历数据而不是在 R 中建立索引
【发布时间】:2021-02-25 19:11:32
【问题描述】:

我正在尝试使用 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]`

【问题讨论】:

    标签: r loops dplyr r-markdown lapply


    【解决方案1】:

    这是一种遍历所有行的方法

    ---
    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 列的矢量版本。

    【讨论】:

    • 这太棒了!!有没有机会你可以看看我的编辑。我需要为每个“运动”生成一个 html 文档,但我不想创建 (29) 个单独的降价文件来实现它!
    • @NewBee 这确实是在问一个不同的问题。与其编辑帖子以提出新问题,不如用新问题开始新帖子。另外,一定要先用谷歌搜索你的新问题。您可能会发现 rmarkdown 文档可以包含 parameters,这将允许您相当轻松地为不同的子组生成多个文档。
    • 谢谢,我去看看!
    • 嗨!我想我回答了你的问题here
    【解决方案2】:

    如果我们需要在全局环境中创建对象,请将数据列子集化为list,重命名并使用list2env

    nm1 <- c('First', 'Second', 'Age', 'submission')
    nm2 <- c('first', 'sec', 'age', submission')
    list2env(setNames(unclass(mydata[nm1]), nm2), .GlobalEnv)
    

    【讨论】:

      【解决方案3】:

      这是我对你上一个问题的回答:

      您可以使用 cat 将 HTML 代码添加到 R 降价块中,以便循环访问您的数据。

      重要

      您必须将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
      }
      
      

      结果如下:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-30
        • 2021-11-22
        • 2017-12-14
        • 2020-04-06
        • 1970-01-01
        • 2019-10-14
        相关资源
        最近更新 更多