我在 R 中創建的函式遇到了一些問題。
fixed <- c("", "disp", "hp", "wt", "qsec", "vs")
f <- function(v) {
fo <- reformulate(c(setdiff(fixed, v),"hp" ), "mpg")
cat("Running", format(fo), "\n")
rf <- lm(fo, data = mtcars)
matrix_coef <- summary(rf)$coefficients
full_coef <- sum(matrix_coef[ , 1])
}
out <- Map(f, fixed)
每當您運行此函式時,它都會為您提供以下串列:
> out
[[1]]
[1] 28.449
$disp
[1] 24.99826
$hp
[1] 28.449
$wt
[1] 56.23431
$qsec
[1] 35.58044
$vs
[1] 32.71946
如何使此函式輸出從第一個串列元素值“[[1]]”中減去的每個串列元素值?這樣串列中的每個元素值都會減去標題為“[[1]]”的第一個串列元素。
[[1]]
[1] 28.449
######## All of the list elements values below should be subtracted from "[[1]]"
$disp
[1] 24.99826
$hp
[1] 28.449
$wt
[1] 56.23431
$qsec
[1] 35.58044
$vs
[1] 32.71946
基本上,公式將是 ([[1]] - x),其中 x 是我們串列中包含的任何其他元素值。
[[1]] - $disp
[[1]] - $hp
[[1]] - $wt
[[1]] - $qsec
[[1]] - $vs
例如,該串列將包含上面獲得的差異。
任何幫助將不勝感激!
uj5u.com熱心網友回復:
您可以做的是在您的函式中定義一個函式來計算系數,而不是撰寫類似的東西return(calcCoef("")-calcCoef(v)),例如:
f <- function(v) {
calcCoef <- function(symbol){
fo <- reformulate(c(setdiff(fixed, symbol),"hp" ), "mpg")
cat("Running", format(fo), "\n")
rf <- lm(fo, data = mtcars)
matrix_coef <- summary(rf)$coefficients
full_coef_h <- sum(matrix_coef[ , 1])
return(full_coef_h)
}
return(calcCoef("")-calcCoef(v))
}
固定應該比類似的東西:fixed <- c("disp", "hp", "wt", "qsec", "vs")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430482.html
下一篇:React組件中的SVG
