在R中:我有一个矩阵,其中一列按8种类型分类: a,b,c,d,e,f,g,h。我需要使用其他列中的数据对每种类型进行不同的计算。我想使用switch()函数来自动化遍历每种类型的循环,并说明每种类型的差异计算;然而,我在网上看到的所有内容只显示了每种开关的一行开关计算的语法示例。
下面是一个使用switch()帮助中提供的代码的示例。我知道mean()是一个函数,但就本例而言,它不是一个函数,因为我只是想说明我不知道它的语法(在我的在线研究中没有明确说明):
centre <- function(x, type) {
switch(type,
mean = {
total.sum<-sum(type)
mean = total.sum/length(type)
},
median = median(x),
trimmed = mean(x, trim = .1))
}发布于 2012-06-27 09:21:06
我认为错误的沟通来自于你例子中的一个打字错误:
mean = {
total.sum<-sum(type)
mean = total.sum/length(type)
},应该是
mean = {
total.sum<-sum(x)
mean = total.sum/length(x)
},如果您进行了此更改,它的行为将完全符合您的期望。
埃塔:我不确定你的评论中有什么问题。请尝试以下代码:
set.seed(1)
centre <- function(x, type) {
switch(type,
mean = {
total.sum<-sum(x)
mean = total.sum/length(x)
},
median = median(x),
trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
print(centre(x, "mean"))
print(centre(x, "median"))
print(centre(x, "trimmed"))输出为:
[1] -0.4844658
[1] -0.236111
[1] -0.3632328https://stackoverflow.com/questions/11201790
复制相似问题