r - 如何在r中的嵌套公式中处理字符串变量名
问题描述
我正在尝试使用变量名称列表运行loop
回归lm
。请看下面的代码。
order <- c(4, 6, 8, 10, 12, 14, 16) # position of variables in my data frame
for(i in order) {
m7 <- df %>% filter(names(df)[i] > 0) %>%
pdata.frame(index=c("index","Year")) %>%
plm(formula= log(names(df)[i]) ~ log(names(df)[i-1]) +
frez + log(dd) + I((log(dd))^2) +
preci + I(preci^2) +
+ m7 + max.c + spei + lt + qt,
data=., effect = c("individual"),model = "within") %>%
coeftest(., vcov = function(x) vcovHC(x, method = 'arellano', cluster = 'group', type = 'HC3'))
}
我收到一条错误消息。我想问题可能出在log
.
Error in log(names(df)[i]) :
non-numeric argument to mathematical function
我的变量名是
> names(df)
[1] "index" "Year" "barley_harv" "barley_yield" "cotton_harv" "cotton_yield"
[7] "oat_harv" "oat_yield" "peanut_harv" "peanut_yield" "rice_harv" "rice_yield"
[13] "sorghum_harv" "sorghum_yield" "sunflower_harv" "sunflower_yield" "AOT40" "frez"
[19] "dd" "spei" "m7" "max.c" "preci" "SUM60"
[25] "W126" "lt" "qt"
任何想法我应该如何解决这个问题???
解决方案
类似(代码片段):
## .. outside
other_vars <- c("frez","log(dd)", "I((log(dd))^2)",
"preci", "I(preci^2)",
"m7","max.c","spei","lt","qt")
## ... inside loop ...
ff <- reformulate(c(sprintf("log(%s)",names(df)[i-1]),other_vars),
response=sprintf("log(%s)",names(df)[i]))
m7 <- (df
%>% filter(names(df)[i] > 0)
%>% pdata.frame(index=c("index","Year"))
%>% plm(formula= ff, data=., effect = c("individual"),
model = "within")
## ... coeftest stuff here
)
推荐阅读
- math - 沿 x 轴均匀分布项目
- sql - 在 SQL 中建模课程表
- abap - 使用 FM COCF_SN_CREATE_PP 创建班次注释时出现“无效目录条目”错误
- ios - 协议类型“Encodable”的值不能符合“Encodable”;只有结构/枚举/类类型可以符合协议
- javascript - jQuery 多日期生成
- c++ - 指向 char 数组中特定位置的 C++ 指针数组
- html - 如何强制引导行中的每个图像具有相同的高度?
- python - Scrapy:为每个蜘蛛使用不同的设置顺序运行蜘蛛
- r - 如何使用高阶函数重命名我自己的函数中的列?
- c++ - 我需要一个更快的解决方案来解决以下问题