R语言通识课代码记录(1)

# Data structure
# vector
ID <- c(1:50)
print(ID)

# seq() function
score1 <- seq(from=-10, to=10, by=2)
score2 <-seq(-10,10, length.out=10)
# rep() function
score3 <- rep("A",50)
?rep
score4 <- rep(c("A","B","C"), times=10)
score5 <- rep(c("A","B","C"), each=10)
# generate random values
# Uniform distribution
score6 <- runif(100, min=0, max=1)
# Normal(Gaussion) distribution N(0,1)
score7 <- rnorm(100,mean=0, sd=1)
# sampling 抽样
gender <- sample(c("man","woman"),10000,replace=TRUE, prob=c(0.3,0.7))
# table() function (law of large number)
table(gender)

# list(numbers, strings, booleans(布尔运算))
mylist1 <- list(c(1:5), c("apple","banana"), c(TRUE, FALSE))
# nested lists 嵌套列表
mylist2 <- list(list(list("Hi")))
is.recursive(mylist2)   # recursive 递归的,循环的

# Factor
skill <- rep(c("High", "Low"), 50)
skill <- factor(skill)

# matrix
A <- matrix(c(1:9), nrow=3, ncol=3, byrow=TRUE)
B <- matrix(c(1:9),3,3)
C <- matrix(c(1:6), 2, 3)
D <- matrix(c(1:6), 3, 2)
E <- diag(c(1:4))

# matrix addition and multiplication
# matrix addition (matrices must be the same size)
A-B
A+C
# matrix multiplication
# A%*%b (the number of columns of A must be the same with 
# the number of rows of B)
C%*%D
D%*%C
# elementwise multiplication(matrices must be the same size) 元素相乘(点乘)
C*C

# Data frame
score1 <- seq(from=-10, to=10, by=2)
score2 <-seq(-10,10, length.out=11)
score3 <- rep("A",11)
score6 <- runif(11, min=0, max=1)
score7 <- rnorm(11,mean=0, sd=1)

mydata1 <- data.frame(score1, score2, score3, score6, score7)
colnames(mydata1) <- c("ID", "gender", "math", "English", "physics")
View(mydata1)

# Indexing
series1 <- c(10:1)
series1[3]
series1[6]
A[2,3] # the 1st number refers to the row, 2nd refers to the columns
mydata1$gender[5]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值