my_sqrt,用以计算输入参数的开方,要求检验输入是否为非负数。my_sqrt<-function(x){
if(x>=0) return(sqrt(x)) else print('请输入非负数')
}
my_sqrt(4)
## [1] 2
my_sqrt(-4)
## [1] "请输入非负数"
lmR,输入参数为 \(y\in\mathbb{R}^p\) 和 \(X \in \mathbb{R}^{n\times p}\),函数是用以求解以下问题\[ \min_{\beta\in \mathbb{R}^p} \|y-X\beta\|^2 \] 返回求得的\(\beta\)值,要求检验 \(y\)的维数和 \(X\)的行数一致。如果存在不可逆的情形,返回错误信息“矩阵不可逆!”
lmR<-function(y,X){
if(det(t(X)%*%X)==0) print("矩阵不可逆!")
if(length(y)!=nrow(X)) print("样本数量不一致")
else return(solve(t(X)%*%X)%*%t(X)%*%y)
}
lmR(y=c(1:4),X=matrix(1:25,ncol=5))
## [1] "矩阵不可逆!"
## [1] "样本数量不一致"
lmR(y=c(4,7,9,3,5),X=matrix(runif(25,-1,1),ncol=5))
## [,1]
## [1,] 6.6720061
## [2,] 7.3720965
## [3,] -17.7998600
## [4,] -13.6558686
## [5,] 0.8992578
lmRcpp。注意事项
library(Rcpp)
library(RcppEigen)
sourceCpp(code='
// [[Rcpp::depends(RcppEigen)]]
#include <RcppEigen.h>
using namespace Eigen;
using namespace std;
// [[Rcpp::export]]
VectorXd lmRcpp(VectorXd y,MatrixXd X){
MatrixXd XX=(X.transpose()*X);
if(XX.determinant()==0){
VectorXd result = VectorXd::Zero(2);
Rprintf("矩阵不可逆");
return result;
}
if(y.size()!=X.rows()){
VectorXd result = VectorXd::Zero(2);
Rprintf("样本数量不一致");
return result;
}
else{
VectorXd res=(X.transpose()*X).inverse()*X.transpose()*y;
return res;
}
}
')
lmRcpp(y=c(1:5),X=matrix(1:25,ncol=5))
## 矩阵不可逆
## [1] 0 0
lmRcpp(y=c(1:4),X=matrix(runif(25,-1,1),ncol=5))
## 样本数量不一致
## [1] 0 0
lmRcpp(y=c(4,7,9,3,5),X=matrix(runif(25,-1,1),ncol=5))
## [1] 7.430117 3.270574 -5.356781 9.957739 -1.021789
注意事项
test:为每个单独的基准测试命名的字符串。如果对应的表达式以命名参数的形式传递给benchmark,则会使用该名称;否则,将使用转换为字符串的表达式本身。
relative:包含相对于最短基准值的基准值的列。此计算中使用的基准值取自使用相对参数指定的列。
replications: 重复次数
library(rbenchmark)
n=2000
p<-c(10,100,1000)
res=list()
for(i in 1:3){
X <- MASS::mvrnorm(n, mu=rep(0,p[i]), Sigma = diag(1,p[i]))
beta <- runif(p[i], 1,3)
y <- X%*%beta + rnorm(p[i])
res[[i]]=benchmark(lmR(y,X),
lmRcpp(y,X),
columns=c("test","elapsed","relative"),
order="relative",
replications=100)
}
res
## [[1]]
## test elapsed relative
## 2 lmRcpp(y, X) 0.01 1
## 1 lmR(y, X) 0.10 10
##
## [[2]]
## test elapsed relative
## 2 lmRcpp(y, X) 0.97 1.000
## 1 lmR(y, X) 4.26 4.392
##
## [[3]]
## test elapsed relative
## 2 lmRcpp(y, X) 96.25 1.000
## 1 lmR(y, X) 500.03 5.195