我正在創建一個 R-Markdown 檔案來幫助報告我們學校的期末考試結果。對于數學考試,我需要一個條件陳述句來顯示適當的圖表,因為如果學生的筆試成績高于某個閾值,則不需要參加口試(Oral = NA)。所以我有一個 if 陳述句來檢查 Oral_Exam 變數的總和(對于必須參加考試的人,為 1,否則為 0)是否大于零,如果是,則創建一個 3D 散點圖,其中必須參加考試的學生口試用紅色標出,后面是同型別的另一個情節,僅與必須參加口試的學生一起,根據口試成績著色。如果沒有學生必須參加口試,則在稍后的 if 陳述句中進行檢查,并且只生成一個情節。我的代碼如下所示:
```{r warning = FALSE, message = FALSE, echo = FALSE, eval = params$subj == "Matematika"}
if(sum(fulldata$Oral_exam) > 0){
fulldata_color = fulldata %>% mutate(Oral_exam, = as.character(Oral_exam), color = recode(Oral_exam, '1' = "red", '0' = "green"))
div(plot_ly(data = fulldata_color, x = ~Long_A_percent, y = ~Long_B_percent, z = ~Short_percent, marker = list(color = ~color), type="scatter3d", mode="markers", text = ~Name, width = 800, height = 800) %>% layout(
scene = list(aspectmode = "cube", xaxis = list(range = c(0,100), title = 'Long A (x)'),yaxis = list(range = c(0,100), title = 'Long B (y)'), zaxis = list(range = c(0,100), title = 'Short (z)'))), align = "center")
enter code here
Oral_data = fulldata %>% filter(!is.na(Oral_percent))
div(plot_ly(data = Oral_data, x = ~Long_A_percent, y = ~Long_B_percent, z = ~Short_percent,color = ~Oral_percent, type="scatter3d", mode="markers", text = ~Name, width = 800, height = 800) %>% layout(
scene = list(aspectmode = "cube", xaxis = list(range = c(0,100), title = 'Long A (x)'),yaxis = list(range = c(0,100), title = 'Long B (y)'), zaxis = list(range = c(0,100), title = 'Short (z)'))), align = "center")
}
這段代碼在編織時只會創建第二個圖,它看起來就像我想要的那樣。但是,如果我將它分成兩個條件相同的 if 陳述句,并放置一個繪圖命令(以及用于創建資料框的相應命令),則兩個圖都可以正確顯示
我可以通過使用兩個 if 陳述句而不是兩個來解決它,但最好知道它為什么不起作用,特別是因為我在同一個代碼塊中使用了多個繪圖(盡管不在同一個 if 陳述句中) 在同一個檔案中,并且它始終按預期作業。
uj5u.com熱心網友回復:
您可以將繪圖物件存盤在變數中并在外部列印它們if:
```{r}
p1 <- NULL
p2 <- NULL
if(TRUE) {
p1 <- plot_ly(x = 1, y = 1, type = "scatter", mode = "marker")
p2 <- plot_ly(x = 1, y = 10, type = "scatter", mode = "marker")
}
p1
p2
```
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/488578.html
