R switch statement with varying outputs throwing error

心不动则不痛 提交于 2019-12-24 14:13:53

问题


I am having trouble with the below switch statement:

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])
            )
    })

If my 'num.bins' is 3, I'd like the following output:

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"

however, I'm getting an error. Thank you very much for your help.


回答1:


You need to decide what version of switch you are using. If you decide to go with the numeric version, then you need to have the indexing start with 1. (A zero index will not succeed.) The numeric version does not use the names strategy but is more like choosing items with "[" or "[[":

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

   print( switch( (i %% 3) +1,
           paste0("M", names[i]),
           paste0("F", names[i]),
           paste0("E", names[i])
            ))
    })

[1] "F1"
[1] "E1"
[1] "M1"
[1] "F2"
[1] "E2"
[1] "M2"
[1] "F3"
[1] "E3"
[1] "M3"

If you want the character version (for which either factor or as.character might be a route to coercing your modulus expression), then you would use the val=expr syntax.




回答2:


You're getting an error because you can't use digits like 0 or 1 as names of arguments.

However, there's a simple way to do what you're trying to do without a switch statement:

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"



回答3:


Please read the ?switch help page. If you pass a numeric value as the first parameter, named arguments are ignored (and you cannot have numbers as named arguments anyway). You can convert to character if you really want.

c.names <- sapply(1:(3*num.bins), function(i){
   switch( as.character(i %% 3),
           "1" = paste0("M", names[i]),
           "2" = paste0("F", names[i]),
           "0" = paste0("E", names[i])
            )
    })


来源:https://stackoverflow.com/questions/27491637/r-switch-statement-with-varying-outputs-throwing-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!