I need to run a self-made function across rows and create an output column in the same data frame (column name tt_daily). This is some made up example.
#data
data1 <- read.csv(text = "
doy,tmx,tmn,relHum,srad
148,31.3,13.8,68.3,30.4
149,31.1,17.2,62.2,30
150,30.1,16.1,69.7,20.9
151,27.3,16.2,77.1,26.1
152,33.4,18.4,65.9,27.4
153,27.2,18,70.3,26.6
154,30.3,13,71.5,28.4
155,36.2,22,62.2,28.8
156,32.9,22.2,61.1,24.9
157,30.5,16.2,63.2,27.9
158,25.7,19.3,71,18.3
159,29.1,18.3,87.2,12.7
160,28.5,20.3,70.2,24.8
")
This is the function:
# function to run row wise
tb<- 11
topt<- 30
tmax<- 42
tt<-function(tmx, tmn, tb, topt, tmax){
tmean<- (tmx + tmn) / 2
if(tmean <= tb) {t1 = 0}
if(tmean >tb & tmean <=topt) {t1 = tmean - tb}
if(tmean>topt & tmean<max) {t1 = (topt - tb) / (topt - tmax) * (tmean - tmax)}
if(tmean >= tmax) {t1 <- 0}
return(t1)
}
This is two options of what I did:
#Option 1
library(dplyr)
tt.example <- data1 %>%
mutate(tt_daily = purrr::pmap(function(tmx, tmn, tb, topt, tmax) tt))
and this is the error:
Error: Problem with
mutate()columntt_daily. itt_daily = purrr::pmap(function(tmx, tmn, tb, topt, tmax) tt). x argument ".f" is missing, with no default
This is the option 2:
#Option 2
tt.example <- data1 %>%
rowwise() %>%
mutate(tt_daily = tt(tmx, tmn, tb, topt, tmax))
This is the error I got:
Error: Problem with
mutate()columntt_daily. itt_daily = tt(tmx, tmn, tb, topt, tmax). x comparison (3) is possible only for atomic and list types i The error occurred in row 1.
Thanks for any advice.