条件语句
ifelse(条件,结果为yes执行的函数,结果为no执行的函数)
x = c(6:-4)
x
#ifelse(条件,结果为yes执行的函数,结果为no执行的函数)
ifelse(x>=0,x,NA)
sqrt(ifelse(x>=0,x,NA))
解释判断X>=0,如果结果为yes数值不变,如果结果为no数值变为NA
实例
ifelse可以多个嵌套
ifelse(ifelse(x>=0,x,NA)>3,x,NA)
嵌套实例
size <- c(0.05, 0.6, 0.3, 0.9)
# size <=0.2 Small
# 0.2< size <=0.8 Medium
# size >0.8 Large
ifelse(size<=0.2,"Small",ifelse(size<=0.8,"Medium","Large"))
嵌套实例2
应用实例
数据源a=read.table("test.txt",header=T,sep="\t",row.names=1)
a
plot(a$height)
color=ifelse(a$gender=="male","blue","red")
color
plot(a$height,col=color)
代码执行结果
图
循环语句
for 和while
for (i in 1:5) print (1:i)
i=1
while(i<=5){
print(1:i)
i=i+1
}
实例
实际应用
#0.2小,0.2-0.8中,大于0.8为大
x <- c(0.05, 0.6, 0.3, 0.9)
for(i in 1:length(x)){
if(x[i] <= 0.2){
cat("Small\n")
} else if(x[i] <= 0.8){
cat("Medium\n")
} else {
cat("Large\n")
}
}
genelist=c("TP53","EGFR","TGFB","MSH2","PTEN")
for(gene in genelist){
filename=paste(gene,".pdf",sep="")
cat(filename,"\n")
}
score=c(55,82,93,78,100,99,28)
for (i in 1:length(score)) {
if(score[i]<60){
cat("Poor\n")}
else if (score[i]<80){
cat("Medium\n")}
else if (score[i]<90){
cat("Good\n")}
else {
cat("Excellent\n")}
i=i=1
}
score=c(55,82,93,78,100,99,28)
1:length(score)
for (i in 1:length(score)){
if (score[i]<60) {
cat("poor\n")}
else if (score[i]<80) {
cat("Medium\n")
}
else if (score[i]<90) {
cat("Good\n")
}
else if (score[i]>=90) {
cat("Excellent\n")
}
}
ifelse 语句简化
ifelse(score>=90,"Excellent",ifelse(score>=80,"good",ifelse(score>=60,"Medium","poor")))
网友评论