2015-03-02 49 views
0

我在嘗試使用基於函數的條件計算創建新列時遇到問題。使用函數創建列

我有一些小數據集用於內插基於高度(CalcAlt)的參考溫度(Tref)。

該函數在我嘗試執行單個計算時起作用,但當我嘗試將函數應用於數據集以創建新列Tref時出現問題。

代碼摘錄如下。

歡迎任何建議!

我得到一個錯誤「適用錯誤(FUN = FUN_Tref,Airlines $ AC_MODEL,Airlines $ CalcAlt): dim(X)必須具有正值長度」。

這是我第一次使用apply函數。

我哪裏錯了?我是一個相對的R,所以可以承認失去了!

史蒂夫

CalcAlt <- c(200,200,400,400,600,600,800,800,1000,1000) 
    AC_MODEL <-c("320-232","321-231","320-232","321-231","320-232","321-231","320-232","321-231","320-232","321-231") 
    Airlines <- data.frame(AC_MODEL , CalcAlt) 

    #Create dataframe showing Tref 
    V2533_alt <- c(-2000,-1000,0,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000,13000,14000,14500) 
    V2533_Tref <- c(19.2, 17.1,15,13.8,11.4,11.9,12,11.9,13.9,15.9,17.8,19.5,21.2,21.8,22.8,25.1,28.5,30.7) 

    V2533 <- data.frame(V2533_alt, V2533_Tref) 
    V2533 

    V2527_alt <- c(0,5200,14500) 
    V2527_Tref <- c(31, 25,25) 

    V2527 <- data.frame(V2527_alt, V2527_Tref) 
    V2527 

    #Create function to calculate Tref based on aircraft type and calculated altitude 
    FUN_Tref <- function(AC_type, CalcAlt){ 
    if(AC_type =="320-232"){ 
      #systematic calculation 
      Tref <- approx(V2527_alt, V2527_Tref, xout = CalcAlt) 

      } 
    if(AC_type =="321-231"){ 
      #systematic calculation 
      Tref <- approx(V2533_alt, V2533_Tref, xout = CalcAlt) 
      } 

    Tref <- as.numeric(Tref[2]) 
    return(Tref) 
    } 
    #END-OF_FUNCTION 
    ############################ 
    #Apply function to create new column Tref 
    Airlines$Tref <- apply(FUN = FUN_Tref, Airlines$AC_MODEL, Airlines$CalcAlt) 
+0

http://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega你可能會發現有幫助 – Khashaa 2015-03-02 11:49:49

回答

1

使用mapply

Airlines$Tref <- mapply(FUN = FUN_Tref, Airlines$AC_MODEL, Airlines$CalcAlt) 
# AC_MODEL CalcAlt  Tref 
#1 320-232  200 30.76923 
#2 321-231  200 14.76000 
#3 320-232  400 30.53846 
#4 321-231  400 14.52000 
#5 320-232  600 30.30769 
#6 321-231  600 14.28000 
#7 320-232  800 30.07692 
#8 321-231  800 14.04000 
#9 320-232 1000 29.84615 
#10 321-231 1000 13.80000 

從幫助:

mapply適用樂趣......每一個參數的第一要素,第二要素,第三個要素,等等。

PS:我還沒有檢查過,如果這可能是矢量化。

+0

就是這樣!非常感謝 – SteveG 2015-03-02 12:05:47