R语言中switch函数的用法

 

001、

switch ("a",                      ## 匹配a
  "a" = 1:5,
  "b" = 3:8,
  "c" = 100-110
)

switch ("b",                      ## 匹配b
        "a" = 1:5,
        "b" = 3:8,
        "c" = 100-110
)

switch ("c",                      ## 匹配c
        "a" = 1:5,
        "b" = 3:8,
        "c" = 100:110
)

 

等价:

switch ("a",
  a = 1:5,                               ## a去掉了引号
  b = 3:8,
  c = 100-110
)

switch ("b",
        a = 1:5,
        b = 3:8,
        c = 100-110
)

switch ("c",
        a = 1:5,
        b = 3:8,
        c = 100:110
)

 

 

002、

switch (1,                            ## 也可以利用序列索引
  "a" = 1:5,
  "b" = 3:8,
  "c" = 100-110
)

switch (2,
        "a" = 1:5,
        "b" = 3:8,
        "c" = 100-110
)

switch (3,
        "a" = 1:5,
        "b" = 3:8,
        "c" = 100:110
)

 

003、 可以匹配代码块

par(mfrow = c(1,3))
switch ("a",                      
        a = {plot(1:10, cex = 3, pch = 16, col = "red")},      ## 匹配代码块
        b = {plot(1:10, cex = 3, pch = 16, col = "blue")},
        c = {plot(1:10, cex = 3, pch = 16, col = "purple")}
)

switch ("b",                      
        a = {plot(1:10, cex = 3, pch = 16, col = "red")},
        b = {plot(1:10, cex = 3, pch = 16, col = "blue")},
        c = {plot(1:10, cex = 3, pch = 16, col = "purple")}
)

switch ("c",                      
        a = {plot(1:10, cex = 3, pch = 16, col = "red")},
        b = {plot(1:10, cex = 3, pch = 16, col = "blue")},
        c = {plot(1:10, cex = 3, pch = 16, col = "purple")}
)

 

posted @ 2022-06-08 11:27  小鲨鱼2018  阅读(1678)  评论(0)    收藏  举报