统计建模与R软件(薛毅 陈立萍) 第二章习题


2_1.R
x=cbind(c(1,2,3));
print(x);
y=cbind(c(4,5,6));
print(y);
z=2*x+y+cbind(c(1,1,1));
print(z);
print(crossprod(x,y));
print(tcrossprod(x,y));


2_2.R
A=matrix(1:20,nrow=4,ncol=5);
print(A);
B=matrix(1:20,nrow=4,ncol=5,byrow=T);
print(B);
C=A+B;
print(C);
E=A*B;
print(E);
F=A[1:3,1:3];
print(F);
G=cbind(B[1:4,1:2],B[1:4,4:5]);
print(G);
#或者
G=B[,-c(3)];
print(G);


2_3.R
x=c(rep(c(1),times=5),rep(c(2),times=3),rep(c(4),times=2));
print(x);


2_4.R
H=matrix(,ncol=5,nrow=5);
for(i in 1:5) {for(j in 1:5) {H[i,j]=c(1/(i+j-1)) }};
print(H);
print(det(H));
print(solve(H));
print(eigen(H));


2_5.R
student=data.frame(
′序号′=c(1:5),
′姓名′=c(“张三”,”李四”,”王五”,”赵六”,”丁一”),
′性别′=c(“女”,”男”,”女”,”男”,”女”),
′年龄′=c(14:16,14:15),
′身高(cm)′=c(156,165,157,162,159),
′体重(kg)′=c(42.0,49.0,41.5,52.0,45.5)
);
print(student);


2_6.R
=read.table(“C:\R\2_5Data.txt”,header=T);
print(M);
write.csv(M,”C:\R\2_5CSV.csv”);


2_7.R
fun_2_7R <- function(){
n =
scan(“”,what=integer(0),nlines=1);
if( n <= 0 ){
print(“要求输入一个正整数”);
}
else{
repeat{
if( n == 1 ){
print(“运算成功”);
break;
}
if( n%%2 == 0 ){
n = n/2;
print(n);
}else{
n = 3*n + 1;
print(n);
}
}
}
}