R:如何让这个函数输出从第一个列表元素值中减去的每个列表元素值?
R: How can I make this function output each list element value subtracted from the first list element value?
我在使用 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
例如,列表将包含上面获得的差异。
如有任何帮助,我们将不胜感激!
你可以做的是在你的函数中定义一个函数来计算系数,而不是写类似 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")
我在使用 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
例如,列表将包含上面获得的差异。
如有任何帮助,我们将不胜感激!
你可以做的是在你的函数中定义一个函数来计算系数,而不是写类似 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")