0
votes

I'm trying to apply a function to a column with multiple columns where one argument is only changing being the given column vector.

I tried:

Temp = c(2, 3, 5) 
s = c("aa", "bb", "cc") 
b = c(TRUE, FALSE, TRUE) 
df = data.frame(s, b, Temp)  
sapply(X=df$Temp, FUN=GJNeeded,SqFt=212265, RValue=2, Temp_Grow=14)

Error in get(as.character(FUN), mode = "function", envir = envir) : object 'GJNeeded' of mode 'function' was not found

My custom function is:

  GJNeeded = function(SqFt, RValue, temp_outside, Temp_Grow){
      if (temp_outside<Temp_Grow) {
      BTU=(temp_outside-Temp_Grow)*SqFt/RValue
  GJ=BTU/1000000*1.0551
}#end if
}#end GJNeeded
1
It is working for me sapply(X=df$Temp, FUN=GJNeeded,SqFt=212265, RValue=2, Temp_Grow=14) [1] -1.343765 -1.231784 -1.007824 Can you try on a fresh R session - akrun

1 Answers

0
votes

The OP's function is working with sapply, but we can make it vectorized instead of looping through each value

GJNeeded <- function(SqFt, RValue, temp_outside, Temp_Grow){
  i1 <- temp_outside < Temp_Grow
  res <- temp_outside #else part is not clear
  BTU <- (temp_outside[i1] - Temp_Grow) * SqFt/RValue
  res[i1] <- BTU/1000000*1.0551
  res 
}

GJNeeded(SqFt = 212265, RValue = 2, temp_outside = df$Temp, Temp_Grow = 14)
#[1] -1.343765 -1.231784 -1.007824