统计建模与R软件习题二答案

# 习题2
# 2.1
x=c(1,2,3)
y=c(4,5,6)
e=c(rep(1,3))
z=2*x+y+e;z
x%*%y # 若x,y如答案那样定义为矩阵,则不能用%*%,因为,维数不对应,
x%o%y 

# 答案
x<-matrix(1:3,nrow=3)
y<-matrix(4:6,nrow=3)
e<-matrix(c(1,1,1),nrow=3)
z<-2*x+y+e;z
crossprod(x,y)#内积
outer(x,y)#外积

# 2.2
A=matrix(1:20,4,5);A
B=matrix(1:20,4,5,byrow=T);B
C=A+B;C
D=crossprod(A,B);D# D=A%*%B;D 错误 维数不对应,题目有错,本来就不可能AB
E=A*B;E
F=A[1:3,1:3];F
G=B[,c(1,2,4,5)];G # G<-B[1:4,-3];G 注意-3的用法

# 答案
A<-matrix(1:20,nrow=4)
B<-matrix(1:20,nrow=4,byrow=T)
C<-A+B;C
#D<-AB#不存在AB这种写法
E<-A*B;E
F<-A[1:3,1:3];F
G<-B[1:4,-3];G

# 2.3
x=c(rep(1,5),rep(2,3),rep(3,4),rep(4,2));x
#答案同上

# 2.4
Hilbert=function(n=5){
  H=matrix(0,nrow=n,ncol=n)
  for (i in 1:n){
    for (j in 1:n) 
      H[i,j]=1/(i+j-1)
  }
  H # 返回值,
  list(Hmatrix=H,det=det(H),sol=solve(H),eig=eigen(H)) # 多元返回值
}
H=Hilbert(5);H
det(H)
solve(H)
eigen(H)

# 学会了function,对上述进行以下修改
funcH=function(n=5) {
	H=matrix(0,n,n)
	for (i in 1:n) {
		for (j in 1:n) {
			H[i,j]=1/(i+j-1)
		}

	}
	H # 返回值,输入H 
	# list(Hmatrix=H,det=det(H),sol=solve(H),eig=eigen(H)) 
	# 也可以以列表形式输出多个返回值,同时能给每个元素定义元素名
	# 如 list(Hilbert=H)
  list(Hilbert=H)
}
funcH()

#2.4答案 5价Hilbert矩阵
n<-5
x<-array(0,dim=c(n,n))
for(i in 1:n){
  for(j in 1:n){
    x[i,j]<-1/(i+j-1)
  }
}
x
det(x)#矩阵行列式
solve(x)#逆矩阵
eigen(x)#特征值与特征向量

# 2.5 data.frame()
studentdata=data.frame('姓名'=c('张三','李四','王五','赵六','丁一'),
                       '性别'=c('女','男','女','男','女'),'年龄'=c(14,15,16,14,15),
                       '身高'=c(156,165,157,162,159),'体重'=c(42,49,41.5,52,45.5))
#studentdata=data.frame('序号'=1:5,'姓名'=c('张三','李四','王五','赵六','丁一'),
#                       '性别'=c('女','男','女','男','女'),'年龄'=c(14,15,16,14,15),
#                       '身高'=c(156,165,157,162,159),'体重'=c(42,49,41.5,52,45.5))
# 不需要输入序号。
write.table(studentdata,'Re2.5.txt')

# 答案
student<-data.frame(name=c("zhangsan","lisi","wangwu","zhaoliu","dingyi"),
                    sex=c("f","m","f","m","f"),
                    age=c("14","15","16","14","15"),
                    height=c("156","165","157","162","159"),
                    weight=c("42","49","41.5","52","45.5"))

# 2.6 
st=read.table('Re2.5.txt',header=T)
write.csv(st,'Re2.5.csv')

#2.6 答案
student1<-write.table(student,file="student1.txt")
student2<-read.table("student1.txt",head=T)
student3<-write.csv(student2,file="student3.csv")

# 2.7
func=function(n) { 
  if (n<=0) "要求输入一个正整数"
  else {
    while(n!=1) {
      if (n%%2==0) n=n/2
      else n=3*n+1}
    "运算成功"
  }
} # R中定义的函数,没有专门的返回值设置,只相当于代码复制粘贴,
func(8) #返回值为代码的输出值

# 答案
#2.7
func<-function(n){
  if(n<=0) list("要求输入一个正整数") 
  else{
    repeat{
      if(n==1) break
      else if(n%%2==0){n<-n/2}
      else n<-3*n+1}
    list("运算成功")
  }
}

 

posted @ 2015-02-28 17:25  monlh  阅读(1218)  评论(0编辑  收藏  举报