gpt4 book ai didi

r - switch 语句给出意外的 ',' 错误

转载 作者:行者123 更新时间:2023-12-04 10:30:40 26 4
gpt4 key购买 nike

我正在尝试创建一个简单的开关来根据季度确定开始日期。

我的代码如下:

qtr_start <- function(qtr, yr){
switch(qtr,
1 = paste(yr, "0101", sep = ""),
2 = paste(yr, "0104", sep = ""),
3 = paste(yr, "0107", sep = ""),
4 = paste(yr, "0110", sep = ""))
}

这给出了错误:

Error: unexpected '=' in:
"switch(qtr,
1 ="
> 2 = paste(yr, "0104", sep = ""),
Error: unexpected ',' in " 2 = paste(yr, "0104", sep = ""),"
> 3 = paste(yr, "0107", sep = ""),
Error: unexpected ',' in " 3 = paste(yr, "0107", sep = ""),"
> 4 = paste(yr, "0110", sep = ""))
Error: unexpected ')' in " 4 = paste(yr, "0110", sep = ""))"

我真的很难看出这与帮助版本有何不同:

centre <- function(x, type) {
switch(type,
mean = mean(x),
median = median(x),
trimmed = mean(x, trim = .1))
}

感谢所有帮助!

最佳答案

您不能使用数字作为案例名称。把它们放在一边(R 将对 1 使用第一种情况,对 2 使用第二种情况,依此类推,或者使用字符串 [edit] 并使用 as.character 在号码上。

所以

 qtr_start <- function(qtr, yr){
switch(qtr,
paste(yr, "0101", sep = ""),
paste(yr, "0104", sep = ""),
paste(yr, "0107", sep = ""),
paste(yr, "0110", sep = "")) }

qtr_start <- function(qtr, yr){
switch(as.character(qtr),
"1" = paste(yr, "0101", sep = ""),
"2" = paste(yr, "0104", sep = ""),
"3" = paste(yr, "0107", sep = ""),
"4" = paste(yr, "0110", sep = ""))
}

关于r - switch 语句给出意外的 ',' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45965675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com