R switch语句具有不同的输出抛出错误

yap*_*aph 1 r switch-statement

我在下面的switch语句中遇到问题:

names <- rep(1:num.bins, 3)
names <- sort(names)
c.names <- sapply(1:(3*num.bins), function(i){

   switch( i %% 3,
           1 = paste0("M", names[i]),
           2 = paste0("F", names[i]),
           0 = paste0("E", names[i])
            )
    })
Run Code Online (Sandbox Code Playgroud)

如果我的'num.bins'是3,我想要以下输出:

print(names)
[1] 1 1 1 2 2 2 3 3 3

print(c.names)
[1] "M1" "F1" "E1" "M2" "F2" "E2" "M3" "F3" "E3"
Run Code Online (Sandbox Code Playgroud)

但是,我收到了一个错误.非常感谢您的帮助.

Dav*_*son 5

您收到错误是因为您不能使用数字01作为参数名称.

但是,有一种简单的方法可以在没有switch语句的情况下执行您要执行的操作:

num.bins <- 3
c.names <- paste0(c("M", "F", "E"), rep(1:num.bins, each = 3))
# [1] "M1" "F1" "E1" "M2" "F2" "E2" "M3" "F3" "E3"
Run Code Online (Sandbox Code Playgroud)