《统计建模与R软件》练习答案-第2章

Exercise 1.

x=c(1,2,3)
y=c(4,5,6)
e=c(1,1,1)
z=2*x+y+e
print(z)
pn=crossprod(x,y)
pw=tcrossprod(x,y)
print(pn)
print(pw)


Exercise 2.

A=matrix(c(1:20), nrow=4, ncol=5)
print(A)

B=matrix(c(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=B[1:4, -3]
print(G)

Exercise 3.

x=c(rep(1,5), rep(2,3), rep(3,4), rep(4,2))
print(x)

Exercise 4.

n=5
H=matrix(0, nrow=n, ncol=n)
print(H)
for(i in 1:n) {
  for(j in 1:n) {
    H[i,j]=1/(i+j-1)
  }
}
print(H)

H1=solve(H)
print(H1)

E=eigen(H)
print(E$values)
print(E$vectors)

Exercise 5.

name=c("\u5F20\u4E09","\u674E\u56DB","\u738B\u4E94","\u8D75\u516D","\u4E01\u4E00")
gender=c("\u5973","\u7537","\u5973","\u7537","\u5973")
age=c(14,15,16,14,15)
height=c(156,165,157,162,159)
weight=c(42.0,49.0,41.5,52.0,45.5)
student=data.frame(name,gender,age,height,weight)
print(student)
setwd("d:/")
write.table(student, file="table_2.3.txt")

Exercise 6.

student2=read.table(file="table_2.3.txt")
print(student2)
write.csv(student2,file="table_2.3.csv")

Exercise 7.

#exercise 2.7
RT <- function(n)  {
  if (n>0) {
    repeat {
          if (n==1)  break
          else {
            if (n%%2==0)  n=n/2
            else n=3*n+1
          }
        }  
      print("Succeed to compute!")
  } else {
      print("Please input a positive integer number!")
  }
}

RT(10)
RT(11)
RT(0)
RT(-1)


你可能感兴趣的:(R)