如何修改函数以提取R中的某些回归系数

如何修改函数以提取R中的某些回归系数,r,function,regression,coefficients,R,Function,Regression,Coefficients,我在从多元线性回归中提取一些系数时遇到了一些麻烦。 这是我的代码的简单可复制版本: d1 <- structure(list(Date=c("2012-01-01", "2012-06-01", "2013-01-01", "2013-06-01", "2014-01-01", "2014-06-01"), x1=c(NA, NA, 17L, 29L, 27L, 10L),

我在从多元线性回归中提取一些系数时遇到了一些麻烦。 这是我的代码的简单可复制版本:

     d1 <- structure(list(Date=c("2012-01-01", "2012-06-01",
                  "2013-01-01", "2013-06-01", "2014-01-01", "2014-06-01"),
                     x1=c(NA, NA, 17L, 29L, 27L, 10L), 
                     x2=c(30L, 19L, 22L, 20L, 11L,24L), 
                     x3=c(NA, 23L, 22L, 27L, 21L, 26L),
                     x4=c(30L, 28L, 23L,24L, 10L, 17L), 
                     x5=c(NA, NA, NA, 16L, 30L, 26L)),
                row.names=c(NA, 6L), class="data.frame")
                rownames(d1) <- d1[, "Date"]   
                d1 <- d1[,-1]


df2012 <- d1[1:2,]
df2013 <- d1[3:4,]
df2014 <- d1[4:5,]

condlm <- function(i){    
  if(sum(is.na(df2012[,i]))==dim(df2013)[1]) # ignore the columns     only containing NA's
    return()
  else
    lm.model <- lm(df2013[,i]~df2012[,i])
  summary(lm.model)
}

lms <- lapply(1:dim(df2013)[2], condlm)
lms


zzq <- sapply(lms, coef)
zzq <- do.call(rbind.data.frame, zzq)
zzq <- zzq[grepl("(Intercept)", rownames(zzq)) ,] 
[[1]]
[[5]]
给我
空值

有没有办法修改函数condlm,它给我一个NA而不是
NULL

最后,用
zzq
purrr:map\u dfr
broom::tidy
提取截取后,似乎就是您想要的

purrr::map_dfr(lms, ~ broom::tidy(.x)[1,])

# # A tibble: 5 x 5
#   term        estimate std.error statistic p.value
#   <chr>          <dbl>     <dbl>     <dbl>   <dbl>
# 1 NA              NA          NA        NA      NA
# 2 (Intercept)     16.5       NaN       NaN     NaN
# 3 (Intercept)     27         NaN       NaN     NaN
# 4 (Intercept)     38.        NaN       NaN     NaN
# 5 NA              NA          NA        NA      NA
purrr::map\u dfr(lms,~broom::tidy(.x)[1,]
##tibble:5 x 5
#术语估计标准误差统计p值
#                          
#1不,不,不,不
#2(截距)16.5纳南
#3(拦截)27南南
#4(拦截)38。楠楠楠楠
#5不,不,不,不
             Estimate Std. Error t value Pr(>|t|) 
(Intercept)  NA              NaN     NaN      NaN
(Intercept)2 16.54545        NaN     NaN      NaN
(Intercept)3 27.00000        NaN     NaN      NaN
(Intercept)4 38.00000        NaN     NaN      NaN
(Intercept)5 NA              NaN     NaN      NaN
purrr::map_dfr(lms, ~ broom::tidy(.x)[1,])

# # A tibble: 5 x 5
#   term        estimate std.error statistic p.value
#   <chr>          <dbl>     <dbl>     <dbl>   <dbl>
# 1 NA              NA          NA        NA      NA
# 2 (Intercept)     16.5       NaN       NaN     NaN
# 3 (Intercept)     27         NaN       NaN     NaN
# 4 (Intercept)     38.        NaN       NaN     NaN
# 5 NA              NA          NA        NA      NA