2017-06-14 18 views
1

我目前正試圖提高自己對有效測試幾個模型的能力。我提供樣本代碼的嘗試可描述如下:向Vectorize()傳遞不同種類的參數

對於給定的因變量(data中的第11列),估計了由其解釋性輸入變量而不同的線性模型。我的願望是有一對參數ab,它們決定了在我的數據框data中選擇解釋變量的開始和結束列。這些參數組合我保存在parameters中。我想添加一個列,其中包含某些度量的評估(此處爲df.residual),並給出其行中的參數。

然而,我在向量化問題時失敗了。更具體地說,我通過ab正確,但不是data

# Example data 
data = as.data.frame(mtcars) 

# Setting the parameters for choosing x-columns 
# a is the start column, b the end column 
parameters = tidyr::expand(tibble(a=1:5, b = 1:5 * 2),a,b) %>% 
dplyr::filter(a<b) 


# Define the function called to yield the result 
another_fun = function(a, b, data) {  
# Vectorize, here's some trouble 
    case_fun_another = Vectorize( 
    function(a, b, data=data) { 
     x = as.matrix(data[,a:b]) 
     y = as.matrix(data[,11]) 
     lm.fit(x=x,y=y)$df.residual 
    }, SIMPLIFY = FALSE 
) 

output = case_fun_another(a, b) 
return(output) 
} 

# Calculate result 
parameters = dplyr::mutate(parameters, result=another_fun(a, b, data)) 

國債收益率:

promise already under evaluation: recursive default argument reference or earlier problems?

我發現這個話題的問題是不是很理解我。也許隨着問題的描述變得更容易。

任何想法如何處理它?我也會開放其他選項,比使用矢量化:-)

非常感謝提前。

+0

@李哲源Zheyuan Li:榮譽 - 有幫助,我學到了很多,謝謝:-)只要我能,我會接受這個答案。 – MaHo

回答

2

這是一個替代方案,不涉及嵌套函數和Vectorize。

# get all the possible pairwise combination of independent variables with combn 
ind.var <- names(data)[-11] %>% 
     combn(., 2) %>% 
     t 

head(ind.var) 

#  [,1] [,2] 
# [1,] "mpg" "cyl" 
# [2,] "mpg" "disp" 
# [3,] "mpg" "hp" 
# [4,] "mpg" "drat" 
# [5,] "mpg" "wt" 
# [6,] "mpg" "qsec" 


# paste values of each row of ind.var, with separator "+" 

x <- do.call(paste, c(as.list(data.frame(ind.var, stringsAsFactors = FALSE)), sep="+")) 
y <- "carb" 

# write out all the linear model formula: 

forms <- mapply(function(a,b) paste(a, b, sep="~"), y, x) %>% 
     setNames(NULL) 

all.lm <- lapply(forms, function(x) eval(bquote(lm(.(x), data=data)))) 

all.lm[[1]] 

# Call: 
# lm(formula = "carb~mpg+cyl", data = data) 
# 
# Coefficients: 
# (Intercept)   mpg   cyl 
#  3.63978  -0.09968  0.18995 

感謝@Roland您指出的bquote使用用於保持lm.object公式通話。

+0

反正你不應該解析。你的最後一句話可以這樣解決:'f < - Sepal.Length〜。; eval(bquote(lm(。(f),data = iris)))'(爲簡單起見,使用不同的示例)。應始終避免解析文本。 – Roland

+0

該示例運行良好,謝謝。我必須研究是否可以將其擴展到所需的參數化。 – MaHo

+1

@羅蘭感謝您提醒我'bquote'。我會盡可能清理代碼。 –