2017-01-16 69 views
0
variables.null.model <- paste('utalter', 'lcsex', 'utcigreg', 'utbmi', 'month', sep = '+') 
variables.full.model <- paste('utalter', 'lcsex', 'utcigreg', 'utbmi', 'month', 'ltedyrs','occ_status', 'marital_status', 'social_cat','GC_linc125_07', 'GC_linc250_07', 'GC_linc500_07', 'GC_linc1000_07', 'GC_linc5000_07', 'GC_pop500_08','utalkkon', 'activity', 'utpyrs', 'cvd', 'utmstati', 'utmfibra', 'utantihy', 'utmeddia', 'utmadins','utwhrat','ul_choln', sep='+') 
pollutants_3 <- c('GC_PM10_09', 'GC_PM25_09', 'GC_Coarse_09', 'GC_BS25_09', 'GC_NOX_09', '$GC_NO2_09') 

null <- paste(variables.null.model, pollutants_3, sep='+') 
full <- paste(variables.full.model, pollutants_3, sep='+') 

fun.model.summary <- function(x) { 
formula <- as.formula(paste("log_sfrp5 ~", x)) 
lm <- lm(formula, data = kalonji.na) 
coef(summary(lm)) 
} 

lm.summary <- lapply(full, fun.model.summary) 

我正在處理一些空氣污染數據,並希望運行線性迴歸函數並總結係數。我有以下代碼上面,但我得到這個錯誤:線性迴歸功能故障

Error in parse(text = x, keep.source = FALSE) : :1:269: unexpected '$'

任何想法我可以解決這個問題?

+0

'pollutants_3'由什麼組成?我也想'lapply(c(null,full),...)'應該可以工作 –

+0

你的'full'變量是一個長度爲1的字符向量。那麼,爲什麼你要使用'lapply'呢? – Istrel

+0

@Istrel再次看,它的長度大於1. –

回答

0

您最後的污染物是'$GC_NO2_09'。請注意迷路$標誌。

但正如我在評論中所說,我強烈建議不要在這裏使用字符串。通過as.name將字符串轉換爲R標識符,直接從R對象構建公式。

您可以通過使用Reducecall將名稱列表合併爲一個和。例如爲:

make_addition = function (lhs, rhs) 
    call('+', lhs, rhs) 

variables_null_model = c('utalter', 'lcsex', 'utcigreg', 'utbmi', 'month') 
interaction_terms_full_model = Reduce(make_addition, lapply(variables_null_model, as.name)) 

fun_model_summary = function (x) { 
    formula = call('~', quote(log_sfrp5), call('+', interaction_terms_full_model, as.name(x))) 
    lm = lm(formula, data = kalonji_na) 
    coef(summary(lm)) 
} 

lm_summary = lapply(pollutants_3, fun_model_summary) 

對於位的背景,這裏使用字符串顛覆了類型系統和由無類型字符串替換適當的,不同的類型。這被稱爲stringly typing,它是一種反模式,因爲它隱藏了錯誤。你的問題就是這樣一個錯誤的例子。

+0

感謝你們的幫助......我現在在光明中 – Dee