# 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")
}
R语言上课代码记录4
最新推荐文章于 2024-10-01 19:19:37 发布