【发布时间】:2021-11-14 14:09:15
【问题描述】:
我需要跨行运行一个自制函数,并在同一个数据框中创建一个输出列(列名tt_daily)。这是一些虚构的例子。
#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
")
这是函数:
# 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)
}
这是我所做的两个选择:
#Option 1
library(dplyr)
tt.example <- data1 %>%
mutate(tt_daily = purrr::pmap(function(tmx, tmn, tb, topt, tmax) tt))
这是错误:
错误:
mutate()列tt_daily有问题。 我tt_daily = purrr::pmap(function(tmx, tmn, tb, topt, tmax) tt)。 x 参数“.f”丢失,没有默认值
这是选项2:
#Option 2
tt.example <- data1 %>%
rowwise() %>%
mutate(tt_daily = tt(tmx, tmn, tb, topt, tmax))
这是我得到的错误:
错误:
mutate()列tt_daily有问题。 我tt_daily = tt(tmx, tmn, tb, topt, tmax)。 x 比较 (3) 仅适用于 atomic 和 list 类型 i 错误发生在第 1 行。
感谢您的建议。
【问题讨论】:
-
@akrun,不,它们被设置为数据集之外的对象。这是错的吗?