将变量列表一次一个地输入到同一个公式中,以测试公式输出如何变化
Input list of variables one at a time into the same formula to test how formula output changes
如何从具有值的变量列表中一次输入一个变量(例如 (apples=5,6,7)
、(oranges=9,10,4)
、(bananas=(3,2,5)
,与 Trend=(1,2,3)
匹配for (revenue=32,44,56)
) 到模型中并在 R 中保存每个模型的摘要?例如我想要 apples
,然后 oranges
,然后 bananas
在以下模型中进行测试
model=gam(price~s(Trend,k=2)+s(apples,k=2),
family="quasipoisson")
不必每次都为每个变量键入一个新模型,因为我有超过 100 个变量我想在这个模型中测试,并且只想通过将苹果换成其他水果来修改模型。
我还想保存每个模型的输出并将其自动编译成 table 以跟踪模型中测试的新变量以及整个模型摘要或者只是我想要从摘要中获得的一个特定指标值(例如 summary$GCV)。
假设您有一个数据框 df
和一堆列,包括 Trend
、Price
和一些水果列,例如 apples
、bananas
,和 oranges
。您可以在感兴趣的列名称上使用 lapply()
,将每一列提供给一个简单的函数,该函数利用 as.formula
创建感兴趣的公式,并 returns 感兴趣的数据。这是一个例子:
f <- function(col,df) {
form = as.formula(paste0("Price~s(Trend,k=2)+s(",col,",k=2)"))
data.frame(col = col, gcv = gam(form, data = df, family="quasipoisson")$gcv)
}
现在,应用感兴趣的函数列,并将 do.call(rbind())
包装到 return 单个 table
do.call(rbind, lapply(c("apples","bananas", "oranges"), f, df=df))
输出:
col gcv
1 apples 1.658002
2 bananas 1.649134
3 oranges 1.637182
输入:
set.seed(123)
df = data.frame(
Trend = sample(1:20, 100, replace=T),
Price = sample(30:60, 100, replace=T),
apples = sample(5:15, 100, replace=T),
oranges = sample(2:9, 100, replace=T),
bananas = sample(4:8, 100, replace=T)
)
如何从具有值的变量列表中一次输入一个变量(例如 (apples=5,6,7)
、(oranges=9,10,4)
、(bananas=(3,2,5)
,与 Trend=(1,2,3)
匹配for (revenue=32,44,56)
) 到模型中并在 R 中保存每个模型的摘要?例如我想要 apples
,然后 oranges
,然后 bananas
在以下模型中进行测试
model=gam(price~s(Trend,k=2)+s(apples,k=2),
family="quasipoisson")
不必每次都为每个变量键入一个新模型,因为我有超过 100 个变量我想在这个模型中测试,并且只想通过将苹果换成其他水果来修改模型。
我还想保存每个模型的输出并将其自动编译成 table 以跟踪模型中测试的新变量以及整个模型摘要或者只是我想要从摘要中获得的一个特定指标值(例如 summary$GCV)。
假设您有一个数据框 df
和一堆列,包括 Trend
、Price
和一些水果列,例如 apples
、bananas
,和 oranges
。您可以在感兴趣的列名称上使用 lapply()
,将每一列提供给一个简单的函数,该函数利用 as.formula
创建感兴趣的公式,并 returns 感兴趣的数据。这是一个例子:
f <- function(col,df) {
form = as.formula(paste0("Price~s(Trend,k=2)+s(",col,",k=2)"))
data.frame(col = col, gcv = gam(form, data = df, family="quasipoisson")$gcv)
}
现在,应用感兴趣的函数列,并将 do.call(rbind())
包装到 return 单个 table
do.call(rbind, lapply(c("apples","bananas", "oranges"), f, df=df))
输出:
col gcv
1 apples 1.658002
2 bananas 1.649134
3 oranges 1.637182
输入:
set.seed(123)
df = data.frame(
Trend = sample(1:20, 100, replace=T),
Price = sample(30:60, 100, replace=T),
apples = sample(5:15, 100, replace=T),
oranges = sample(2:9, 100, replace=T),
bananas = sample(4:8, 100, replace=T)
)