I have generated some predicted values using a custom linear regression function, reg()
, and iterating it over multiple variables with a for-loop. They are saved in forage.pred
, a vector of more than 5000 values.
I am now trying to convert this into a dataframe, but I don't know how to.
Several loop tutorials that I found on the Internet use dummy example with one vector and index based on a single vector, so they don't apply to my situation.
forage
# A tibble: 5,421 × 24
# year standid trt plot sedge legume woody forbs
# <dbl> <dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 1986 2 CCSP 1 30 14.4 0 30
# 2 1986 7 CCSP 1 0 0 20 0
# 3 1986 12 CCSP 1 18 0 0 158.
# 4 1987 2 CCSP 1 2 0 0 32
# 5 1987 7 CCSP 1 0 40 0 80
# 6 1987 12 CCSP 1 0 2 0 52
# 7 1988 2 CCSP 1 0 2 424 2
# 8 1988 7 CCSP 1 104 0 0 0
# 9 1988 12 CCSP 1 4 4 64 2
# 10 1989 2 CCSP 1 0 0 0 2
# … with 5,411 more rows, and 16 more variables:
# panicum <dbl>, grass <dbl>, litter <dbl>,
# burned <dbl>, nonwoody <dbl>, pp_grow <dbl>,
# pp_watyear <dbl>, pp_spring <dbl>, pp_summer <dbl>,
# pp_winter <dbl>, pp_grow.s50 <dbl>,
# pp_grow.s30 <dbl>, pp_grow.s10 <dbl>,
# pp_grow.a10 <dbl>, pp_grow.a30 <dbl>, …
# ℹ Use `print(n = ...)` to see more rows, and `colnames()` to see all variable names
yvar <- forage[, 5:10]
new.pp <- forage[, 19:24]
# Fit linear model and create predicted values
reg <- function(i, j) {
lm.forage <- lm(i ~ year + pp_grow,
data = forage)
forage.pred <- (predict(lm.forage,
newdata = list(pp_grow = j)))
}
# Loop this over multiple variables
for (i in yvar) {
for (j in new.pp) {
reg(i, j)
}
}