我參考這個答案:
linear_model <- function(TIME) lm(Education ~ poly(TIME,2), data=table2)
m <- lapply(split(table2,table2$LOCATION),linear_model)
new_df <- data.frame(TIME=c(2019))
my_predict <- function(TIME) predict(m,new_df)
sapply(m,my_predict) #error here
uj5u.com熱心網友回復:
您是否正在尋找這樣的解決方案?
library(tidyverse)
library(broom)
df %>%
mutate(LOCATION = as_factor(LOCATION)) %>%
group_by(LOCATION) %>%
group_split() %>%
map_dfr(.f = function(df){
lm(Education ~ TIME, data = df) %>%
glance() %>%
add_column(LOCATION = unique(df$LOCATION), .before=1)
})
LOCATION r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC deviance df.residual nobs
<fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int> <int>
1 AUT 0.367 0.261 4.88 3.47 0.112 1 -22.9 51.8 52.0 143. 6 8
2 BEL 0.0225 -0.173 3.90 0.115 0.748 1 -18.3 42.6 42.4 76.0 5 7
3 CZE 0.0843 -0.0683 3.22 0.552 0.485 1 -19.6 45.1 45.3 62.2 6 8
uj5u.com熱心網友回復:
您的函式語法有一些錯誤。函式通常寫成 function(x),然后你用你想要使用它的資料替換 x。
例如,在linear_model你定義的函式中,如果你單獨使用它,你會寫:
linear_model(data)
但是,因為您在lapply函式內部使用它,所以查看起來有點棘手。Lapply 只是創建一個回圈并將該linear_model函式應用于您從split(table2,table2$LOCATION).
同樣的事情發生在my_predict.
無論如何,這應該適合你:
linear_model <- function(x) lm(Education ~ TIME, x)
m <- lapply(split(table2,table2$LOCATION),linear_model)
new_df <- data.frame(TIME=c(2019))
my_predict <- function(x) predict(x,new_df)
sapply(m,my_predict)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/341299.html
下一篇:如何計算帶有值的列
