我在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]]";?使得该列表中的每个元素值被标题为"0"的第一列表元素减去;[[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
例如,该列表将包含上述差异。
任何帮助都将不胜感激!
您可以在函数中定义一个函数来计算系数,而不是编写类似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")