Reputation: 109
I am having problems with trying to create a new column using a conditional calculation based on a function.
I have some small datasets that are used to interpolate a reference temperature (Tref) based on altitude (CalcAlt).
The function works when I try to do a single calculation but I get problems when I try to apply the function to a dataset with the aim of creating a new column Tref.
An extract of the code is below.
Any advice welcome!
I get an error "Error in apply(FUN = FUN_Tref, Airlines$AC_MODEL, Airlines$CalcAlt) : dim(X) must have a positive length".
This is the first time I have used the apply function.
Where am I going wrong? I am a relative newby to R so can admit to being lost!
Steve
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)
Upvotes: 0
Views: 78
Reputation: 132606
Use 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
From the help:
mapply applies FUN to the first elements of each ... argument, the second elements, the third elements, and so on.
PS: I haven't checked if this could be vectorized.
Upvotes: 1