2022年4月3日 星期日

原生管線操作 (native pipe operator)

主題

R-4.1版本以上開始支援原生管線操作(native pipe operator),管線操作可簡化R程式的撰寫。一般可以使用 magrittr 套件%>% 運算式進行管線操作,目前 R-4.1 以上版本可以使用 |> 進行管線操作。

R程式碼

# (1)傳統指派依序建立物件

x <- iris$Petal.Width[iris$Species== "virginica"]

x_density <- density(x)

plot(x_density, main = "Density plot")

grid()


# (2)使用 magrittr 套件

library(magrittr)

iris$Petal.Width[iris$Species== "virginica"] %>%

  density() %>%

  plot(main = "Density plot using '%>%'") %>%

  grid()


# (3)使用原生管線操作 |>

iris$Petal.Width[iris$Species== "virginica"] |>

  density() |>

  plot(main = "Density plot using native pipe operator '|>'")>

  grid()

# end