使用函数创建列

Create column using function

我在尝试使用基于函数的条件计算创建新列时遇到问题。

我有一些小数据集,用于根据高度 (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)

使用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 applies FUN to the first elements of each ... argument, the second elements, the third elements, and so on.

PS: 我还没有检查这是否可以矢量化。