I am having some trouble with a function that I created in 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)
Whenever you run this function it gives you the following list:
> 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
How can I make this function output each list element value subtracted from the first list element value "[[1]]"? So that each of the element values that are in this list are subtracted by the first list element titled "[[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
Basically, the formula would be ([[1]] - x) with x being any other element value included in our list.
[[1]] - $disp
[[1]] - $hp
[[1]] - $wt
[[1]] - $qsec
[[1]] - $vs
For example, the list would contain the differences obtained above.
Any help at all would be greatly appreciated!
CodePudding user response:
What you could do is to define within your function a function to calculate the coefficient and than writing something like return(calcCoef("")-calcCoef(v))
, e.g.:
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 should be than something like: fixed <- c("disp", "hp", "wt", "qsec", "vs")