c++ - RcppArmadillo faSTLm 结果与 R 的 lm 不同,我做错了什么?

标签 c++ r rcpp armadillo

这是我使用 sourceCpp 获取的 cpp 文件:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

// [[Rcpp::export]]
List mylm(NumericVector yr, NumericMatrix Xr) {

    int n = Xr.nrow(), k = Xr.ncol();

    arma::mat X(Xr.begin(), n, k, false);       // reuses memory and avoids extra copy
    arma::colvec y(yr.begin(), yr.size(), false);

    arma::colvec coef = arma::solve(X, y);      // fit model y ~ X
    arma::colvec resid = y - X*coef;            // residuals

    double sig2 = arma::as_scalar( arma::trans(resid)*resid/(n-k) );
                                                // std.error of estimate
    arma::colvec stderrest = arma::sqrt( sig2 * arma::diagvec( arma::inv(arma::trans(X)*X)) );

    return Rcpp::List::create(
        Rcpp::Named("coefficients") = coef,
        Rcpp::Named("stderr")       = stderrest
    ) ;

}

(代码取自@Romain François 对这个问题的回答:Using `sourceCpp` to compile `fastLm`)

然后在 R 中:

sourceCpp('b.cpp')
set.seed(1)
x = matrix(rnorm(100), 25, 4)
y = rnorm(25)
mylm(y, x)
summary(lm(y~x))

mylm(y, x)
# $coefficients
#           [,1]
# [1,]  0.068978
# [2,]  0.117632
# [3,] -0.029917
# [4,] -0.168648
# 
# $stderr
#         [,1]
# [1,] 0.17970
# [2,] 0.24312
# [3,] 0.15138
# [4,] 0.21266

summary(lm(y~x))

# Call:
# lm(formula = y ~ x)
# 
# Residuals:
#    Min     1Q Median     3Q    Max 
# -0.869 -0.487 -0.271  0.410  1.831 
# 
# Coefficients:
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)   0.1122     0.1718    0.65     0.52
# x1            0.0499     0.1845    0.27     0.79
# x2            0.1076     0.2470    0.44     0.67
# x3           -0.0435     0.1549   -0.28     0.78
# x4           -0.1750     0.2158   -0.81     0.43
# 
# Residual standard error: 0.835 on 20 degrees of freedom
# Multiple R-squared:  0.054,     Adjusted R-squared:  -0.135 
# F-statistic: 0.285 on 4 and 20 DF,  p-value: 0.884

最佳答案

默认情况下,R 的 lm 使用截距拟合模型,即使您传递的设计矩阵不包含初始列 1。所以你会看到以下是相同的:

lm(y ~ x - 1)
mylm(y, x)

如果您想要“常规”模型,则需要修改您的设计矩阵以使其第一列全为 1:

lm(y ~ x)
mylm(y, cbind(1, x))

将给出相同的结果。

关于c++ - RcppArmadillo faSTLm 结果与 R 的 lm 不同,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20034737/

相关文章:

c++ - 忽略 rpath 条目的可执行文件

c# - 一般读取格式正确的二进制文件

r - 寓言中的预测功能是否提供一步预测?

c - R的R_pow()和libc的pow()有什么区别?

c++ - VS2013中在哪里定义宏

c++ - lambda通过this捕获成员变量

r - ggplot2 geom_area 重叠面积图在彼此前面

r - ggsave() as svg 字体配置错误

r - 使用 SHLIB 编译和加载独立的 Rcpp 函数

Rcpp代理模型和R内存分配