簡體   English   中英

R:具有多行的switch語句

[英]R: switch statement with multiple lines

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

我認為錯誤的傳達來自你的例子中的拼寫錯誤:

 mean = {
       total.sum<-sum(type)
       mean = total.sum/length(type)
 },

應該

 mean = {
       total.sum<-sum(x)
       mean = total.sum/length(x)
 },

如果進行此更改,它的行為與您期望的完全相同。

ETA:我不確定你的評論中的問題是什么。 請嘗試以下代碼:

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.3632328

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM