###Sample code for Lab1 #display the current working directory getwd() #change the directory to where the dataset is stored setwd("C:/Users/shouhermione/Documents/TA/Nanjing/Karen") #list all the files in the directory list.files() #list all the files in the work space ls() #logical value 3>2 (1==4)&(is.na(5)) #create a vector/matrix/array x<-1:10 x x<-c(0.3,-2.1,5.7) #concatenate summary(x) sort(x) mean(x) #create a matrix y<-matrix(1:6,nrow=2,ncol=3,byrow=FALSE) y y[2,1] #matrix calculation A<-matrix(1:6,nrow=3,ncol=2) B<-matrix(7:10,2,2) A%*%B A*B z<- array(1:9,dim=c(3,3,3)) #generate a list x<-list(gender=c('F','M'),grade=c(98,100,90),undergrad=FALSE) #read in data frame dat<-read.csv('osteo.csv',header=TRUE) dim(dat) #output the data write.table(dat, 'osteo2.txt',col.names=TRUE, sep='\t') dat<-read.table('osteo2.txt', header=TRUE) ##pick the subset of the data with osteo==1, which returns the index of rows satifying the criteria in the parentheses case<-dat[which(dat$Osteo==1),] ##plotting op<-par(mfrow=c(2,2)) plot(dat$Age, dat$DPA,main='DPA vs. age',xlab='age',ylab='DPA',col='blue') hist(dat$DPA,main='Histogram of DPA') #boxplot(dat$DPA,main='Boxplot of DPA') boxplot(dat$DPA~dat$Osteo,main='Boxplot of DPA by disease status') qqnorm(dat$DPA) qqline(dat$DPA) par(op) #stem plot stem(dat$DPA) #plot x<-seq(from=0,to=1,length=50) w<-2*cos(4*pi*x) #true value e<-rnorm(50,mean=0,sd=.5) #random errors y<-w+e plot(x,y,type='l',ylim=c(-3,4)) lines(x,w,col='blue',lwd=2,lty='dashed') legend('topright',legend=c('with noise','true value'),col=c('black','blue'),lty=c('solid','dashed'),lwd=c(1,2)) #loops m=4 s<-1 for(i in 1:4){ s=s*i } print(s) s<-4 j<-4-1 while(j>=1) { s=s*j j=j-1 } #define your own function fx<-function(x){ y=0 if((x<=8)&(x>0)) y=2*x-1 if((x<=10)&(x>8)) y=x y } fx(9)