R语言上课代码记录4

# A powerful tool in data mining: which()
A <- c(10:20)

# the which() gives you the position of elements of a 
# logical vector that True
which(A>15)
# select the elements in A that are > 15
A[which(A >15)]

# which.max
which.max(A) # the position of the maximum of A
A[which.max(A)] # the maximum of A

# which.min
which.min(A) # the position of minimum of A
A[which.min(A)] # the minimum of A

# Make a dataset
id <- c(1:34)
gender <- sample(c("M","F"), size=34, replace=TRUE, prob=c(0.3,0.7))
gender <- factor(gender)  # factor 类别
score <- sample(c(50:100), 34, replace=TRUE)
mydata <- data.frame(id, gender, score)

# subsetting子集 with which()
# choose only famale students
mydata_female <- mydata[which(mydata$gender=="F"),] 
# choose students with scores > 90 
mydata_good <- mydata[which(mydata$score>=90),]

# create categorical variables
mydata$letter <- NA  # use $ to create a new variable
mydata$letter[which(mydata$score>=90)] <- "A"
mydata$letter[which(mydata$score<90 & mydata$score>=80)] <- "B"
mydata$letter[which(mydata$score<80 & mydata$score>=60)] <- "C"
mydata$letter[which(mydata$score<60)] <- "F"

head(mydata, 5)

# table() gives you frequency of each kind 
table(mydata$gender)
table(mydata$letter)

# Logical Operaters in R: and(&), or(|), and not(!)
A <- c(1:10)
# and(&)
(A>6 & A<=8)
# or(|)
(A>6 | A<=8)
# not(!)
A>5
!(A>5)

# Branching
# if statement
# if(condition is TRUE){then do}
B <- 1
if(B>-5){
  print("B is greater than -5")
}

# if...else...statement
# if(condition is TRUE){
# then do A
# } else {
# do B
# }

C <- -10
if(C>0){
  print("C is positive")
} else {
  print("C is not positive")
}

# if...else if...else...
C <- -9
if(C>0){
  print("C is positive")
} else if(C==0){
  print("C is 0")
} else {
  print("C is negative")
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值